Aneesh
Aneesh

Reputation: 1733

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?

Upvotes: 0

Views: 86

Answers (4)

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

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.

Upvotes: 5

Suresh Atta
Suresh Atta

Reputation: 121998

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.

Upvotes: 2

user2571962
user2571962

Reputation: 79

The static keyword means there will only be one instance of that variable and not one variable per instance.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

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?

Upvotes: 3

Related Questions