如果我改变 ?
至 Object
代码编译。
Q1。有没有办法改变unwind
适用于 <?> getList()
的方法签名?
Q2。如果没有,您是否听说过有关使用 <?>
设计参数化 API 的任何设计原则? ?
public class Main {
public static void main(String[] args) {
unwind(getList());
}
public static List<List<?>> getList() {
return new LinkedList<List<?>>();
}
public static<T> Collection<T> unwind(Collection<? extends Collection<T>> collection) {
return collection.iterator().next();
}
}
附言。我一直坚持处理多次调用 Future<?> java.util.concurrent.ExecutorService.submit(Runnable task)
的结果集合
我有Future<Object>
会更好方法的结果。这里的API设计有问题吗?
最佳答案
我仍然不确定这是关于什么的。使用泛型,您必须非常具体地说明类型。您说您正在尝试了解“利弊”。代码不是那样工作的,至少不是这段代码。这完全取决于您要做什么。
一个可能的解决方案是滥用 @SuppressWarnings("unchecked")
List<List<Future<?>>> llist = getSomething( x );
@SuppressWarnings( "unchecked" )
Collection<?> cx = llist;
另一个是确保您的通用类型 100% 匹配。但我仍然不知道你到底想做什么。是这个吗?
public static List<List<Future<?>>> getSomething( Future<?> x ) {
List<List<Future<?>>> llist = new ArrayList<>();
List<Future<?>> list = new ArrayList<>();
list.add( x );
llist.add( list );
return llist;
}
public static <t> Collection<t> unwind( Collection<? extends Collection<t>> c ) {
return c.iterator().next();
}
public static void main(String[] args) {
Future<?> x = null;
List<List<Future<?>>> llist = getSomething( x );
Collection<Future<?>> clist = unwind( llist );
}
关于java - 方法不适用于泛型方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25466735/