This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Collections.copy() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections.copy()" Watch "Collections.copy()" New topic
Author

Collections.copy()

Bill Compton
Ranch Hand

Joined: Aug 26, 2000
Posts: 186
I'm sure I'm doing something silly: can't get Collections.copy() to work:

Any ideas? In case it matters, java -version says:
java version "1.3.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)
Thanks.
Bill Compton
Ranch Hand

Joined: Aug 26, 2000
Posts: 186
Ok, so I think I figured it out. Collections.copy() requires not only the capacity for an equivalent number of members in the destination, but also that at least that many members already exist in the destination! The javadoc could-a been a little clearer on this point. Reading the Collections.java brought this to light. So, to do a copy that doesn't require pre-existing items to be over-written, something like this is needed:
Brian Jackson
Greenhorn

Joined: Jan 20, 2004
Posts: 1
Here's another way to accomplish what you needed:
thushara wijeratna
Greenhorn

Joined: Jan 28, 2009
Posts: 9
You could use List.addAll(Collection c) to do this as well.


http://thushw.blogspot.com
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38075
    
  22
Welcome to JavaRanch, both of you

I am afraid addAll will have a slightly different effect; old elements in the destination List will still be there.
thushara wijeratna
Greenhorn

Joined: Jan 28, 2009
Posts: 9
yes true. one should clear the dest list first. normally, people who want to use Collections.copy has an empty destination list in mind. Alas, Collections.copy doesn't really do a copy, it is an "element replacer". so we fall back on List.addAll().
Zongjian Feng
Greenhorn

Joined: Jan 15, 2008
Posts: 3
thushara wijeratna wrote:yes true. one should clear the dest list first. normally, people who want to use Collections.copy has an empty destination list in mind. Alas, Collections.copy doesn't really do a copy, it is an "element replacer". so we fall back on List.addAll().

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections.copy()
 
Similar Threads
Traps to be aware of in any SCJP test !!!!! :)
Java version
Collections copy error
how the JIT for the IBM jvm is switched off?
Collections.copy method for lists ? how it works