today i dealt with a Java problem that really confused me. I have the following code:
List<ObjectXY> someList = obj.getListOfObjectsXY(); // getter returns 2 elements
someList.add(new ObjectXY());
obj.getListOfObjectsXY(); // getter now returns 3 elements
When i add an element to a list, the getter gets some kind of overwritten. Is this because someList
acts like a reference on the result of the getter in this case? Or what else causes this effect?
I solved the problem with the following code by using another list:
List<ObjectXY> someList = obj.getListOfObjectsXY(); // result: 2 elements
List<ObjectXY> someOtherList = new ArrayList<ObjectXY>();
someOtherList.addAll(someList);
someOtherList.add(new ObjectXY());
obj.getListOfObjectsXY(); // result: 2 elements
But i am still some kind of confused because i didn't expect Java to behave this way. Can anyone explain to me what i did wrong and why it is so?
Thanks in advance!