l1 = null;
assigns null to the l1
variable. If the list has been stored before in another object, this other object still has a reference to the list, and thus still has access to all the elements that are stored in this list. If the List object object previously referenced by l1
is not reachable anymore, it will be garbage collected. Same for its elements: if they're not reachable anymore, they will be garbage collected.
l1.clear();
is very different: it removes all the elements from the list. If the list has been stored before in another object, this other object has a reference to the list you just cleared, and thus doesn't have access to the elements that were stored in the list anymore (since you removed them). If the elements previously stored in the list are not reachable anymore, they will be garbage collected. The list won't be, since you keep a reference to it (l1
).
So , l1 = null
should be used if you want to reuse the variable, but want to keep the List Object as is. l1.clear()
should be used if you want to remove all the elements from the list.