• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collections.copy()  RSS feed

 
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:
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another way to accomplish what you needed:
 
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.
 
Marshal
Posts: 57244
175
  • 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().
 
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().


 
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad:
The WEB SERVICES and JAX-RS Course
https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!