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

Collections copy error

 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I get a compilation error -> The method copy(List<? super T>, List<? extends T>) in the type Collections is not applicable for the arguments (List<String>, List<Object>)

what does List<? super T> & List<? extends T> signifies... i am simply copying from List<String> to List<Object> which is in my terms a more distinct hierarchy to the most generic Object list which Java should allow?
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My mistake.. it should have been Collections.copy(copyList,testList);

Sorry!
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I modified the code but get IndexOutOfBoundsException: Source does not fit in dest

 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you read the Javadocs for that method? They explain why it won't work.

However, you should be able to get the effect you want like this:
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks it worked. can you tell me why second one is throwing indexoutofbounds exception even if i declare list of big size?

 
Rob Spoor
Sheriff
Pie
Posts: 20510
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You declared it with a big capacity (the number of elements it can hold before its internal structure needs to change). The size (the actual number of elements) is still 0. You'll first need to add several objects before the size increases.
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's capacity, not size. The target list actually has to contain that many elements.

I'm not entirely sure why the method is written like that - it seems a bit pointless - but it's how it's defined.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mathew & Rob - thanks!

it worked after doing below

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic