I accidentally wrote this piece of code .
static List<Integer> foo(List<Integer> fillthis,List<? super Integer> readlist){
for(Object i:readList){
if(i instanceof Integer)
fillthis.add(i);
}
return fillthis;
}
As you can see, it basically takes a list of Integer and another List of Integer or any of its supertype, say a List of Object; Then from the 'readList' it extracts every int value and puts it into the given int List 'fillthis' I used List because even a List or List can contain an integer
Ofcourse, it won't compile because compiler won't let an unverified value from 'readList' into a pure int List 'fillthis' . So it ends up giving me typical error :
actual argument Object cannot be converted to Integer by method invocation conversion
But, tend to think of it, this is a perfectly reasonable piece of code if only one can get around this with the help of helper methods Can someone please help ? I have tried my wits ends
THANK YOU VERY MUCH :)
EDIT ------------------
Thanks Meindratheal, but can anyone suggest a helper method for this one , incase if I don't wish to typecast because a helper method like
static <T,U super T> List<T> foo(List<T> fillthis,List<U> readList);
won't work as generics don't allow 'super' in type parameter list. it only allows extends also ,is there even a helpermethod for this one.
Please do suggest :)
UPDATE
Braj, I don't know how it affects what kind of list I am passing! Ofcourse, I could follow your advice and pass on a List and TBH, this code isn't a piece of any serious software design BUT DEAR, this very simple question does challenge our knowledge of java generics
Maybe read my code again above and I guess you know already what my question is
Ok fine, lets say I have
public static void main(String[] args){
List<Integer> lint=Arrays.asList(1,2,3);
List<Object> lobj=new List<Object>();
lobj.add(new Object());
lobj.add(new Integer(4)); /*will compile perfectly. had I used List<? super Integer> instead of List<Integer>, I can't pass lobj to extract this value of 4. Clear?? */
foo(lint,lobj);
}
The question is simple :Can we create a helper method to make this method work exactly like it is ??