Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections.copy()

 
Bill Compton
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another way to accomplish what you needed:
 
thushara wijeratna
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use List.addAll(Collection c) to do this as well.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic