This week's book giveaway is in the Reactive Progamming forum. We're giving away four copies of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams and have Adam Davis on-line! See this thread for details.
I hope things are going well; I have a question about the toArray() method from the ArrayList class. I am re-reading Gupta's excellent OCAJP7 study-guide and am confused by the two paragraphs at the top of page 221. These paragraphs seem to be trying to explain how modifying either 1) the elements of the returned array from the toArray() method call or 2) modifying the ArrayList that generated the array could effect the original ArrayList data structure or the array or something.... 0_o
I tried this in this program and it only modified the ArrayList I intentionally modified and did not affect the array created from the ArrayList
In the code above only the ArrayList is changed even though StringBuilder is a completely changeable, i.e. mutable, object.
Can someone explain a situation where changing one collection would affect the other please? I did search the site before asking.
Also, are there many questions on the exam that have this method in them?
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array.
This method acts as bridge between array-based and collection-based APIs.
I just have read the 2 paragraphs at the top of page 221.
In short it (correctly) states 2 things:
a) the array created by calling toArray() is not the same array as used by the ArrayList itself, it's a new array. So if you swap, delete, add elements in the array, these changes are only applied to the array (not to the ArrayList, so the ArrayList is still in its orginal state). Of course the same applies when you swap, delete, add elements in the ArrayList (only the ArrayList has changed, no changes to the array). This behaviour is also mentioned in the javadoc of the toArray-method (see my previous post). And that should also be shown in the output of your program
b) the references of the individual ArrayList elements are copied into the array (created by calling toArray-method). That means that both the array and the ArrayList refer to the same elements. So if you change a (mutable) object using the array elements, these changes will also be visible in the ArrayList (because both are referring to the same elements). Of course the same applies when you do the same using the ArrayList So if you add following line of code to your program (just above printing both collections), you'll see the tricky part Mala Gupta explains at the top of page 221: ((StringBuilder)s).delete(1, 3); a1.get(1).delete(2,5);