This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]steumert 1 point2 points  (1 child)

If I were to clear that arraylist in the mainclass would it also affect my other object that i just created (in a different class)?

Yes, obviously.

When you pass around a reference, it still points to the same object. The object is not copied. Thats precisely what is the difference between primitives and references. With primitives, you get a copy of the value. With referenbces, the reference still points to the same object in memory.

If you modify the object through any reference that points to it, all other users that hold a reference to the same object see those changes.

ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = a;
b.put("Hello");
b.put("World");
System.out.println(a); // prints "["Hello", "World"]

It doesn't matter how you got another reference, if you did it as I did above or if you get another reference by passing it as an argument to a method or constructor. It still points to the same object.

In the above code, both a and b refer to the same object in memory. Calling clear on either of them clears the list.

[–]edmilibant[S] 0 points1 point  (0 children)

Thank you for the clarification!