Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java collections stores values or references? [duplicate]

Beginner Java question: when I have

Integer i = 6;
ArrayList<Integer> ar = ArrayList<Integer>();
ar.add(i);

then I write i = 8, ar.get(0) returns 6.

But if I trie the same thing with a class of mine:

class MyC
{
    Integer i;
}
MyC myc = new MyC();
myc.i = 6;
ArrayList<MyC> ar = ArrayList<MyC>();
ar.add(myc);

then do myc.i = 8, ar.get(0) returns 8.

Can you please explain this behavior?

like image 809
hovnatan Avatar asked Jun 17 '26 22:06

hovnatan


1 Answers

The problem has nothing to do with autoboxing, as some answers say.

In the first example you create an Integer and put it in the ArrayList. Then you change the pointer to the Integer, so that i is pointing to another Integer. This don't affects the Integer of the ArrayList.

In the second example you create an object and put it in the ArrayList. Then you change the state of this object by myc.i = 8. This way the object in the ArrayList is changed.

like image 128
F. Böller Avatar answered Jun 20 '26 13:06

F. Böller