7

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?

3
  • off the cuff, it doesn't seem possible to me. Commented Jun 18, 2013 at 16:21
  • How would your class decide which one to use, if you called remove(key)? Commented Jun 18, 2013 at 16:22
  • Doesn't look good Commented Jun 18, 2013 at 16:22

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

This is unlikely to be useful. The purpose of implementing java.util.Queue is so that instances of this class can be passed into methods that expect a java.lang.Queue. Implementing MyQueue isn't going to achieve this.
@AndrzejDoyle I agree, but on the off chance that this solution would work for the OP's use case or spark further discussion I figured I'd post it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.