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,691
  • 2
  • 22
  • 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,107
  • 3
  • 36
  • 55
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
  • 227,678
  • 33
  • 352
  • 470
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
  • 118,038
  • 37
  • 189
  • 297
0

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