java - 如何不使用我得到的构造函数覆盖参数?

标签 java constructor

我有这个构造函数:

    private static int list [] = new int[0];
    public IntList (String[] elems){
        this.list = new int[elems.length];
        int j=0;
        for(String i : elems){
            this.list[j] = Integer.parseInt(i);
            ++j;
        }
    }

如果我定义了一个新的 IntList,我将看不到原始的 args

public static void myTest(IntList args){
  String[] tmpIntList = {"21","22","23","24"};
  IntList newIntListForTest = new IntList(tmpIntList);
  /* for example, if I called myTest with {"1","2","3"},
      and if I print args here then I see only  21,22,23,24*/
}

我怎样才能同时看到它们?

最佳答案

你的list成员是static,意味着它属于类,而不是特定的实例。换句话说,IntList 的所有实例都共享相同的 list,因此每当您创建一个新实例并覆盖 list 时,它都会被覆盖“for所有 IntList”。

长话短说 - 删除 static 修改,你应该没问题:

private int[] list = new int[0];

关于java - 如何不使用我得到的构造函数覆盖参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246976/

相关文章:

java - 如何声明函数参数以接受抛出的函数?

即使放置文件路径后,在Windows中也找不到Java

java - 如何创建内容提供程序以通过隐式 Intent 与另一个应用程序共享 PDF 文件?

java - 生成构造函数

c# - 如果我为集线器定义构造函数,连接将关闭

java - 如何停止 slider 上的无限循环

java - 将 jlist 中选定的元素放入字符串列表中

C++11 构造函数的区别(大括号)

Javascript 在 Child 中调用 Parent 构造函数(原型(prototype)继承) - 它是如何工作的?

C++ 类构造函数参数 : How to access members and methods from another class instance without copying?