java 中同一对象内的对象列表
list of objects inside the same object in java
我有下一个情况:
public class Network {
protected int mask;
protected IPv4Address address;
public Network(IPv4Address address, int maskLength) {
blahblah
}
public mymethod() {
Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
}
在这里,每次我调用 mymethod 时,我都需要创建对我来说效率低下的对象列表。我可以以某种方式创建一次并将其用于我的所有方法吗?抱歉,如果这个问题简单或愚蠢 - 我是 java.
的新手
将变量定义为实例变量:
public class Network {
protected int mask;
protected IPv4Address address;
Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
public Network(IPv4Address address, int maskLength) {
blahblah
}
public mymethod() {
}
使用这个:
public class Network {
protected int mask;
protected IPv4Address address;
private static Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
public Network(IPv4Address address, int maskLength) {
blahblah
}
public mymethod() {
}
将Network
设为static
变量,只会初始化一次
static Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
我有下一个情况:
public class Network {
protected int mask;
protected IPv4Address address;
public Network(IPv4Address address, int maskLength) {
blahblah
}
public mymethod() {
Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
}
在这里,每次我调用 mymethod 时,我都需要创建对我来说效率低下的对象列表。我可以以某种方式创建一次并将其用于我的所有方法吗?抱歉,如果这个问题简单或愚蠢 - 我是 java.
的新手将变量定义为实例变量:
public class Network {
protected int mask;
protected IPv4Address address;
Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
public Network(IPv4Address address, int maskLength) {
blahblah
}
public mymethod() {
}
使用这个:
public class Network {
protected int mask;
protected IPv4Address address;
private static Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}
public Network(IPv4Address address, int maskLength) {
blahblah
}
public mymethod() {
}
将Network
设为static
变量,只会初始化一次
static Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}