Ro.
Ro.

Reputation: 1377

Extending a Generic Collection with another Generic

I need to create my own implementation of a PriorityBlockingQueue<Runnable>

Using my own Interface MyRunnableInterface which extends Runnable, There are two options I see:

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

2 - class MyQueue extends PriorityBlockingQueue<MyRunnableInterface>

Using option 1, with the constructor new MyQueue<MyRunnableInterface> I get the error: Type mismatch: cannot convert from MyQueue to BlockingQueue

Using option 1, with the constructor new MyQueue I get the warning: MyQueue is a raw type. References to generic type MyQueue should be parameterized

Using option 2, with the constructor new MyQueue I get the error: Type mismatch: cannot convert from MyQueue to BlockingQueue

The thing Is, I want to be able to reference my created MyQueue Object calling a method that takes the Typed parameter MyRunnableInterface and not having to do a type cast each time (from T)

I think I'm missing something on the Generics subtlety ?

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);
}

}

More code added above .... Guess I'll just have to live with the warnings ?

Upvotes: 0

Views: 196

Answers (2)

blgt
blgt

Reputation: 8205

With your updated code, you're getting the error because the generic types are different (related, but the compiler doesn't care). You can do a wildcard match:

private static BlockingQueue<? extends Runnable> create() {
    return new MyQueue<MyRunnableInterface>(); //Now no error and no warning
}

Upvotes: 1

Smutje
Smutje

Reputation: 18143

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>();
    }
}

Works for me...

Upvotes: 2

Related Questions