以下是使用泛型扩展基类型的两种形式:
public abstract <T extends Runnable> BlockingQueue<T> getQueueA();
public abstract BlockingQueue<? extends Runnable> getQueueB();
我不明白。有什么不同?这两种方法似乎都返回了扩展Runnable的对象的BlockingQueue。
答案 0 :(得分:3)
BlockingQueue<Thread> threads = thing.getQueueA(); // works
BlockingQueue<Thread> threads = thing.getQueueB(); // does not work
另一方面:
@Override public <T extends Runnable> BlockingQueue<T> getQueueA() {
return new ArrayBlockQueue<Thread>(); // no worky
}
@Override public BlockingQueue<? extends Runnable> getQueueB() {
return new ArrayBlockQueue<Thread>(); // works
}
答案 1 :(得分:2)
虽然两个类型的返回队列都扩展了Runnable,但区别在于第一个版本是类型方法,类型T
在方法和编译器中可用所以当调用方法时,它可以推断类型。
第二个版本没有这些好处:它只返回一个类型未知的队列,但扩展了Runnable。