我不小心写了这段代码。
static List<Integer> foo(List<Integer> fillthis,List<? super Integer> readlist){
for(Object i:readList){
if(i instanceof Integer)
fillthis.add(i);
}
return fillthis;
}如您所见,它基本上接受了一个整数列表和另一个Integer列表,或者它的任何一个超级类型,比如一个对象列表;然后从'readList‘中提取每个int值,并将其放入给定的int列表中--我使用了这个列表,因为即使是一个列表或列表也可以包含一个整数。
当然,它不会编译,因为编译器不会让未经验证的值从'readList‘变成一个纯粹的int列表’填充这个‘。所以它给了我一个典型的错误:
actual argument Object cannot be converted to Integer by method invocation conversion但是,想一想,这是一个非常合理的代码,如果只有一个人可以在帮助方法的帮助下解决这个问题,有人能帮忙吗?我已经试过我的智慧了
(非常感谢:)
编辑?
谢谢我,但是有人能为这个方法提出一个帮助方法吗?如果我不想键入,因为一个帮助方法,比如
static <T,U super T> List<T> foo(List<T> fillthis,List<U> readList);不会工作,因为泛型不允许‘超级’在类型参数列表。它只允许扩展,甚至有一个帮助的方法为这一个。
请建议:)
更新
布拉杰,我不知道它是如何影响我所传递的名单的!当然,我可以按照您的建议传递列表和TBH,这段代码并不是任何严肃的软件设计的一部分,但是亲爱的,这个非常简单的问题确实挑战了我们对java泛型的了解。
也许上面再读一遍我的代码,我想你已经知道我的问题是什么了。
好吧,让我说我有
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);
}这个问题很简单:我们能否创建一个助手方法来使这个方法完全按照它的工作方式工作呢??
发布于 2014-05-03 14:50:49
您必须将i转换为Integer:
static List<Integer> foo(List<Integer> fillthis,List<? super Integer> readlist){
for(Object i:readList){
if(i instanceof Integer)
fillthis.add((Integer) i);
}
return fillthis;
}发布于 2014-05-03 15:19:23
使用 List<? super Integer> 而不是List<? super Integer>来使其更加清晰。
就这样使用吧。
static List<Integer> foo(List<Integer> fillthis, List<Number> readlist) {
for (Number i : readlist) {
if (i instanceof Integer)
fillthis.add(i.intValue());
}
return fillthis;
}https://stackoverflow.com/questions/23445893
复制相似问题