0

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?

Aneesh
  • 1,703
  • 3
  • 24
  • 34

4 Answers4

5

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.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
  • Is this true when `varArray` is not static? – Aneesh Oct 09 '13 at 07:12
  • @Aneesh. If you just assign one reference to another, it won't matter whether its static or non static. They will refer to the same object. You can read sureshatta's answer for more clarification. – Prasad Kharkar Oct 09 '13 at 07:16
3

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?

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

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