java中同一对象内的对象列表

时间:2015-02-13 12:26:43

标签: java oop methods

我有下一个情况:

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的新手。

3 个答案:

答案 0 :(得分:1)

将变量定义为实例变量:

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() {
    }

答案 1 :(得分:1)

Network设为static变量,它只会被初始化一次。

static Network[] privatnetworks = {new Network(new IPv4Address("10.0.0.0"), 8), new Network(new IPv4Address("172.16.0.0"), 12)}

答案 2 :(得分:0)

使用此:

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() {

}