aspose file tools*
The moose likes Beginning Java and the fly likes Collections copy error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections copy error" Watch "Collections copy error" New topic
Author

Collections copy error

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776


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
Bartender

Joined: May 31, 2011
Posts: 1776
My mistake.. it should have been Collections.copy(copyList,testList);

Sorry!
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
I modified the code but get IndexOutOfBoundsException: Source does not fit in dest

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4244
    
    7

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
Bartender

Joined: May 31, 2011
Posts: 1776
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

Joined: Oct 27, 2005
Posts: 19556
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4244
    
    7

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
Bartender

Joined: May 31, 2011
Posts: 1776
Mathew & Rob - thanks!

it worked after doing below

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Collections copy error
 
Similar Threads
generic code
Iterator - Expected a ConcurrentModificationException but it does not throw this exception
Problem with pass-by-reference ?
Inferring the correct type parameter
html:select and html:options or html:optionsCollection