• Post Reply Bookmark Topic Watch Topic
  • New Topic

Objects in a collection  RSS feed

 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have one object, then I add that object to a collection... how many instances of that object do I have?

example:

MyClass c = new MyClass();
c.setString("Before adding to collection");
List<MyClass> myList = new ArrayList<MyClass>();
myList.add(c);

c.setString("Added to the collection");

MyClass b = (MyClass) myList.get(0);
System.out.println(b.getString());

output is "Added to the collection", but if I set c = null after adding c to the collection, I get "Before adding to collection"

It appears that there are 2 objects pointing to the same reference, is that what is happening?

Thanks,
Eric
 
steve souza
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have one instance. c contains a reference to that instance. The ArrayList contains a reference to the same instance. However, if you assign c=null it will have no effect on the reference that is contained in the ArrayList. The reference that is in the arraylist is returned to b.
 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steve, that makes sense.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!