简体   繁体   中英

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 . Will the changes be reflected in 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. Or am I doing something wrong?

Its not about static. The statement ArrayList<String> temp = Dummy.varArray; means that both variables are referring to the same arraylist. As varArray is static, it will have only one copy.

You can read ArrayList<String> temp = Dummy.varArray; as, The variable temp is now referring to the ArrayList object which is being referred by Dummy.varArray

By the way, you need to initialize it using 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?

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

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 .

 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 .

static关键字表示该变量只有一个实例,每个实例没有一个变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM