是否可以从不同的类获取静态数组列表的副本。我试图从不同的类访问数组列表,但总是得到一个空的。我假设我们可以直接访问静态变量...
基本上我想在添加一些内容后获取数组列表的副本。我怎样才能做到这一点?
import java.util.ArrayList;
public class two {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> two = one.getTemp();
for (int i = 0; i < two.size(); i++) {
System.out.println(two.get(i));
}
}
}
import java.util.ArrayList;
public class one {
public static ArrayList<Integer> temp = new ArrayList<Integer>();
public static ArrayList<Integer> getTemp() {
return temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
temp.add(i * 10);
}
for (int i = 0; i < 10; i++) {
System.out.println(temp.get(i));
}
while (true) {
}
}
}
最佳答案
您正在 main 方法中初始化 ArrayList,并希望在第二类中使用该 arraylist,但是当您从中调用 main 方法时,第一类中的 ArrayList 将初始化,然后您无法在第二类中使用它。如果您想在 get 方法调用时初始化它,请创建一个 static
block
import java.util.ArrayList;
public class Two {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(One.temp);
ArrayList<Integer> copy=One.temp;
One.temp.add(100);
System.out.println(copy);
}
}
class One{
public static ArrayList<Integer> temp = new ArrayList<Integer>();
public static ArrayList<Integer> getTemp() {
return temp;
}
static {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
temp.add(i * 10);
}
}
}
输出:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
在第二类的对象中,发生了浅复制,因此当您在静态数组列表中进行任何更改时,它将自动显示在第二类的列表中。
关于java - 从不同的类复制静态数组列表的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23421275/