This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes list and array Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "list and array" Watch "list and array" New topic
Author

list and array

hari harann
Ranch Hand

Joined: Aug 07, 2008
Posts: 54

1)created a list
2)printed the list
2)created an array and changed the list to array
4)altered the first element of list
5)change is reflected in the list
6)BUT NOT IN THE ARRAY. THE SAME OLD VALUE IS PRINTED HERE. it should have been changed in the array, when i change the element in the list..???

can anybody explain why is it so??
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35438
    
    9
it should have been changed in the array, when i change the element in the list..???

No. The array that gets created by toArray is independent of the original List. It contains the same objects, but it will not be updated if the List is updated (the List does not know about the array).

If you look at the source code of ArrayList.toArray you will see that there is no connection between the two.


Android appsImageJ pluginsJava web charts
George Gates
Ranch Hand

Joined: Jul 11, 2008
Posts: 34
Hari Harann,

Good discovery.

The book (K&B) states that only when you use asList(),any change in one (array or list) also gets updated in the other.

This is however not true for toArray(). This exception is not mentioned in the book though.


Regards,<br />George Gates
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: list and array
 
Similar Threads
How to remove common item between 2 ArrayList
LinkedList problem
Collections.frequency and Collections.disjoint
Binary Search
java.util.List method addAll(int,Collection)?