0

Let's say I have three ArrayList and a HashMap as follows:

public HashMap<Integer, ArrayList<String>> m = new HashMap<>();
public ArrayList<JSONObject> A = new ArrayList<>();
public ArrayList<JSONArray> B = new ArrayList<>();
public ArrayList<String> C = new ArrayList<>();

And I do:

m.put(0, C);//setting values to the hashmap
C.clear();//resetting value of C

But this also clear the C inside m hashmap, resulting m = [0, ""]. Why is this the case in Java?

What I was expecting is this

int A = 1;
int B = 2;
int C = A+B //result is 3

Now if i set A=0 this shouldn't affect the final value of C

Can someone please explain this to me?

envyM6
  • 1,099
  • 3
  • 14
  • 35
  • yes it will clear it, that map holds a reference to C, and by doing .clear() you are clearing the object the map is referencing – Javant Jul 21 '16 at 19:23
  • but why? and how can i get around this? – envyM6 Jul 21 '16 at 19:23
  • clone/copy to a new object – Javant Jul 21 '16 at 19:23
  • Can you explain and post an answer with an example please? – envyM6 Jul 21 '16 at 19:24
  • 2
    Java is pass-by-value, so your ArrayList's reference is the same object as the one in the `Map`. Check out http://stackoverflow.com/a/715660/4793951 to see how to deep clone a `List`. – Zircon Jul 21 '16 at 19:25
  • @Zircon not what i'm expecting – envyM6 Jul 21 '16 at 19:27
  • There is no such thing as a _reference to a variable_ in Java. Here's some related reading material: [What is the difference between a variable, object, and reference?](http://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference) – Sotirios Delimanolis Jul 21 '16 at 19:32
  • I just want that `C` List to be reusable. So after first loop I want to clear it and re-use it again. How can I achieve this? – envyM6 Jul 21 '16 at 19:37
  • `C` is storing a reference to a `ArrayList` object. What you `put` into `m` is a copy of that same reference to the same object. If that's not the behavior you want, do what @zircon suggested and create and `put` a copy of the `ArrayList` referenced. – Sotirios Delimanolis Jul 21 '16 at 19:39
  • I'll appreciate an example please? With the given context above – envyM6 Jul 21 '16 at 19:43
  • See the link in Zircon's comment. – Sotirios Delimanolis Jul 21 '16 at 19:54

0 Answers0