• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java object references  RSS feed

 
D VanAssche
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm curious as to why the following code outputs 10 10. Wouldn't the fact that objs was reconstructed to a new object translate to the first instance of container returning an empty List, thus the output should be 10 0? I must be missing something very fundamental here, but this result throws a wrench in my understanding of how objects work. Any explanation or link to some document that explains it would be greatly appreciated...

import java.util.ArrayList;
import java.util.List;

public class DummyRunner
{
/**
* @param args
*/
public static void main(String[] args)
{
List<List> container = new ArrayList<List>();
List<DummyObject> objs = new ArrayList<DummyObject>();
for (int i = 0; i < 10; i++)
{
DummyObject obj = new DummyObject();
obj.setIntValue(i);
obj.setStringValue(String.valueOf(i));
objs.add(obj);
}

container.add(objs);
System.out.println(container.get(0).size());
objs = null;
objs = new ArrayList<DummyObject>();

System.out.println(container.get(0).size());
}
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
objs is just an object reference. If you assign it to point to a new object, it will not affect the reference in the list.
 
D VanAssche
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Keith Lynn:
objs is just an object reference. If you assign it to point to a new object, it will not affect the reference in the list.


I could have sworn that at one time, if I did:
Object obj1 = new Object();
Object obj2 = obj1;
obj1 = null;
then, obj2 would be null. But this is not the case, even though obj1 and obj2 pointed to the same memory address before obj1 was set to null. So because obj1 is just a reference to a memory address, and not the actual value, obj2 remains unaffected. This is probably a stupid question, but is this new to Java 1.5 or has this always been the case? This also sort of changes my view in regard to making things Cloneable. I guess you learn something new every day...
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's always been that way. Assigning to a reference always changes only the reference, never the object the reference originally pointed to.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!