Search code examples
javaandroidarraylistfinal

final reference object get modified


I'm turning crazy on this one.

What I want to do is to get an object from an ArrayList, and add it in 3 others after modifying it.

The problem is that the object I get from my ArrayList is modified aswell when I modify the others... Can't figure out why, is this normal?

Code below:

final Product tmpRef = productsRef.get(i);
Product tmp = tmpRef;
tmp.setPos(products1.size());
Log.d("test2","tmpRef:"+tmpRef.getPos()+";tmp:"+tmp.getPos());

Product tmp2 = tmpRef;
tmp2.setPos(products2.size());
                Log.d("test2","tmpRef:"+tmpRef.getPos()+";tmp:"+tmp.getPos()+";tmp2:"+tmp2.getPos());

Product tmp3 = tmpRef;
tmp3.setPos(products3.size());
                Log.d("test2","tmpRef:"+tmpRef.getPos()+";tmp:"+tmp.getPos()+";tmp2:"+tmp2.getPos()+";tmp3:"+tmp3.getPos());
tmp.setPos(products1.size());

"pos" is just a simple int, with a getter/setter.

LogCat output:

03-21 09:56:14.926: D/test2(6200): tmpRef:9;tmp:9
03-21 09:56:14.926: D/test2(6200): tmpRef:7;tmp:7;tmp2:7
03-21 09:56:14.926: D/test2(6200): tmpRef:0;tmp:0;tmp2:0;tmp3:0

With @FD_, @blackbelt and @Guidobaldo da Montefelt's explainations, I ended creating a simple new Porduct's constructor to be able to copy the object, and not only the reference. Thanks guys.


Solution

  • Essentially, you just store references in your ArrayList, so it does not matter whether you use something like Product tmp = tmpRef;. tmp still points to the same object, thus changes are applied to both.

    In this case, final just means that a pointer cannot be changed once it has been set.

    Just search for deep copy java for possible solutions.