6

Assuming I have an ArrayList of ArrayLists created in this manner:

  ArrayList< ArrayList<String> > listOfListsOfStrings = 
                              new ArrayList< ArrayList<String> >();

If I call:

 listOfListsOfStrings.clear();

Will an attempt to later access any of the Strings inside listOfListsOfStrings always result in a java.lang.NullPointerException?

anubhava
  • 761,203
  • 64
  • 569
  • 643
an00b
  • 11,338
  • 13
  • 64
  • 101
  • 1
    Try it and see what happens. If it doesn't work the way you expect then poste your demo code that shows the problem. As you can see the answer is NO it won't cause an exception. So if you are getting an exception it means you have a coding problem and you are not further ahead by asking a "what if" question. That is why you should always try it yourself. It should on be less than 10 lines of code. – camickr Apr 14 '11 at 20:27

2 Answers2

3

No, just the references will be cleared. If no reference to an object exists anymore it might be garbage collected, but you'd get no NPE, since you then have no way to get a new reference to that object anyway.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • Thanks. Your answer helped me find this incredible answer which helped me find the source of a bug that was driving me crazy: http://stackoverflow.com/questions/333151/java-how-to-pass-byte-by-reference/333217#333217 It turns out that in Java I can't pass a reference to a reference... So when I passed an ArrayList paramter to a superclass method to be filled, it was actually filling a different array... All is well now. – an00b Apr 15 '11 at 01:11
  • And this article may be able to help future n00bs like me: http://javadude.com/articles/passbyvalue.htm – an00b Apr 15 '11 at 01:12
  • You're welcome :) As a side node, although Java is pass-by-value what is really passed if you use objects as parameters is the reference. Thus you can pass an object into the method and modify it there, but you can't create the object inside assign it to the passed reference. In terms of C/C++ you'd pass a pointer to an object by value. -- One possibility to reduce those bugs or make the compiler help you would be to mark all parameters as final (Eclipse can do this automatically for). If you then assign a different value to a parameter the compiler would complain. – Thomas Apr 15 '11 at 06:34
1

No, it will not delete objects in the ArrayList if you still have external references to them. ArrayList.clear() does nothing to the objects being referred to unless they are orphaned, in which case you won't be referring to them later on.

sverre
  • 6,768
  • 2
  • 27
  • 35