java - 用另一个泛型扩展一个泛型集合

标签 java generics

我需要创建我自己的 PriorityBlockingQueue<Runnable> 的实现

使用我自己的界面 MyRunnableInterface延伸Runnable ,我看到有两个选项:

1 - class MyQueue<T extends MyRunnableInterface> extends PriorityBlockingQueue<T>

2 - class MyQueue extends PriorityBlockingQueue<MyRunnableInterface>

使用选项 1 和构造函数 new MyQueue<MyRunnableInterface>我收到错误:类型不匹配:无法从 MyQueue 转换为 BlockingQueue

使用选项 1 和构造函数 new MyQueue我收到警告:MyQueue 是原始类型。对泛型类型 MyQueue 的引用应该参数化

使用选项 2 和构造函数 new MyQueue我收到错误:类型不匹配:无法从 MyQueue 转换为 BlockingQueue

问题是,我希望能够引用我创建的 MyQueue 对象,调用一个采用类型参数 MyRunnableInterface 的方法。并且不必每次都进行类型转换(来自 T)

我想我遗漏了泛型的一些微妙之处?

public class MyQueue<T extends MyQueue.MyRunnableInterface>
extends PriorityBlockingQueue<T> {

public interface MyRunnableInterface extends Runnable {

}

public int test( final MyRunnableInterface r ) {
    return 0;
}

private static BlockingQueue<Runnable> create() {
    return new MyQueue<MyRunnableInterface>(); //Error Here
}

private static BlockingQueue<Runnable> create2() {
    return new MyQueue(); //Warning Here
}

public static void main(final String[] args) {
    final BlockingQueue<Runnable> r = create();
    ((MyQueue) r).test(null);
}

}

上面添加了更多代码...我猜我只能忍受这些警告?

最佳答案

public class MyQueue<T extends Runnable> extends PriorityBlockingQueue<T> {

    public interface MyRunnableInterface extends Runnable {

    }

    public static void main(String[] args) {
        final BlockingQueue<MyRunnableInterface> myRunnableInterfaces = new MyQueue<MyQueue.MyRunnableInterface>();
    }
}

对我有用...

关于java - 用另一个泛型扩展一个泛型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265404/

相关文章:

java - Wicket 口和 CSS 资源

java - 了解 Intellij 中 Maven 的正确工作流程

java - PrimeFaces 自动完成更改默认大小

java - 使用 Spring RestTemplate 向每个 REST 请求添加查询参数

java - 尝试绘制动画位图,但不起作用

delphi - 如何使用 Delphi 一步初始化 TList<T>?

java - 编译带有边界的泛型时出错

c++ - 当 List<List<X>> 时,模板在 C++ 中删除

java - 调用 Java 泛型方法

java - T 扩展 SomeClass 的意义何在?