Pergunta

I am trying to build a class that implements Queue and Map. Both interfaces define the remove(Object) method, but with different return types:

public interface Collection<E> { //Queue extends Collection, which has the problem method

    public boolean remove(Object e);

    //...
}

public interface Map<K,V> {

    public V remove(K key);

    //...
}

public class QueuedMap<K,V> extends AbstractMap implements Queue {

    public V remove(K key) {/* ... */}
    //ERROR: V is not compatible with boolean

    //...
}

The type erasure of K is causing these two method signatures to collide. I can't have one of them because it's an invalid override, and I can't have both because they have the same signature. Is there any way that I can make these two interfaces coexist?

Foi útil?

Solução

I don't believe that's possible in this particular case. If both classes returned Object types you'd have some chance, but since you're mixing basic and object types, there's no compatible type that would support both interfaces.

A different approach may be to implement appropriate interfaces that are compatible, then use composition to store an internal structure and map function calls to that as needed. That would assume that you don't need to satisfy or be usable as both interfaces, but rather that one in particular is the one you need to expose.

However, if you need to make this class replaceable as two incompatible interfaces, it can't be done.

Outras dicas

You could make your own interface MyQueue with all the methods that Queue has minus the remove method and use that. You could give the MyQueue interface a Queue toQueue() method that returns the object converted into a queue.

This conversion process could involve just returning a new instance of an anonymous Queue, which, for each method X, would simply call/return this.[X]. For the remove method you'd call this.remove() but then return a boolean rather than the return value of the this.remove() call.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top