[英]Clarification regarding static variable behaviour in Java
Suppose I have a class : 假设我有一堂课:
class Dummy{
public static ArrayList<String> varArray;
}
In another class I do this : 在另一堂课中,我这样做:
Class Dummy2{
void main()
{
ArrayList<String> temp = Dummy.varArray;
}
}
Now suppose in Dummy2
I add elements to temp
. 现在假设在Dummy2
我向temp
添加了元素。 Will the changes be reflected in Dummy.varArray
? 更改会反映在Dummy.varArray
吗? Because this is what is happening in my program. 因为这就是我的程序中正在发生的事情。 I tried printing the address of the two and they both point to the same address. 我尝试打印两个的地址,它们都指向相同的地址。 Didn't know static
field worked like this. 不知道static
场是这样工作的。 Or am I doing something wrong? 还是我做错了什么?
Its not about static. 它不是关于静态的。 The statement ArrayList<String> temp = Dummy.varArray;
语句ArrayList<String> temp = Dummy.varArray;
means that both variables are referring to the same arraylist. 表示两个变量都引用相同的arraylist。 As varArray
is static, it will have only one copy. 由于varArray
是静态的,因此它将只有一个副本。
You can read ArrayList<String> temp = Dummy.varArray;
您可以阅读ArrayList<String> temp = Dummy.varArray;
as, The variable temp is now referring to the ArrayList object which is being referred by Dummy.varArray as, 变量temp现在引用由Dummy.varArray引用的ArrayList对象。
By the way, you need to initialize it using public static ArrayList<String> varArray = new ArrayList<String>();
顺便说一下,您需要使用public static ArrayList<String> varArray = new ArrayList<String>();
初始化它public static ArrayList<String> varArray = new ArrayList<String>();
before you perform any operations on it. 在对其执行任何操作之前。
ArrayList<String> temp = Dummy.varArray;
will take what is known as a reference copy (or a shallow copy ). 将采用所谓的参考副本 (或浅表副本 )。 That is, they will point to the same object. 也就是说,它们将指向同一对象。
It does not take a deep copy. 它不需要深层副本。 See How to clone ArrayList and also clone its contents? 请参阅如何克隆ArrayList以及克隆其内容?
Yes it is behaving correctly. 是的,它的行为正确。
When you do this 当你这样做
ArrayList<String> temp = Dummy.varArray;
Both pointing to the same reference ,since temp
not a new
list, you just telling that refer to Dummy.varArray
两者都指向同一个引用,因为temp
不是new
列表,您只需要告诉它引用Dummy.varArray
To make them independent, create a new list 为了使它们独立,请创建一个新列表
ArrayList<String> temp = new ArrayList<String>(); //new List
temp.addAll(Dummy.varArray); //get those value to my list
Point to note: 注意事项:
When you do this temp.addAll(Dummy.varArray)
at that point what ever the elements in the varArray
they add to temp
. 当您在此时执行temp.addAll(Dummy.varArray)
时, temp.addAll(Dummy.varArray)
varArray
的元素添加到temp
。
ArrayList<String> temp = new ArrayList<String>(); //new List
temp.addAll(Dummy.varArray); //get those value to my list
Dummy.varArray.add("newItem");// "newitem" is not there in temp
The later added elements won't magically add to temp
. 以后添加的元素不会神奇地添加到temp
。
static关键字表示该变量只有一个实例,每个实例没有一个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.