clearing or set null to objects in java

Firstly, you never set an object to null. That concept has no meaning. You can assign a value of null to a variable, but you need to distinguish between the concepts of “variable” and “object” very carefully. Once you do, your question will sort of answer itself 🙂

Now in terms of “shallow copy” vs “deep copy” – it’s probably worth avoiding the term “shallow copy” here, as usually a shallow copy involves creating a new object, but just copying the fields of an existing object directly. A deep copy would take a copy of the objects referred to by those fields as well (for reference type fields). A simple assignment like this:

ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = list1;

… doesn’t do either a shallow copy or a deep copy in that sense. It just copies the reference. After the code above, list1 and list2 are independent variables – they just happen to have the same values (references) at the moment. We could change the value of one of them, and it wouldn’t affect the other:

list1 = null;
System.out.println(list2.size()); // Just prints 0

Now if instead of changing the variables, we make a change to the object that the variables’ values refer to, that change will be visible via the other variable too:

list2.add("Foo");
System.out.println(list1.get(0)); // Prints Foo

So back to your original question – you never store actual objects in a map, list, array etc. You only ever store references. An object can only be garbage collected when there are no ways of “live” code reaching that object any more. So in this case:

List<String> list = new ArrayList<String>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("Foo", list);
list = null;

… the ArrayList object still can’t be garbage collected, because the Map has an entry which refers to it.

Leave a Comment