2

If I want to instantiate a LinkedList and require access to the methods in both List and Dequeue interfaces, and do not want to type to the concrete implementation, and do not want to cast between interfaces, is there a way?

i.e.:

LinkedList ll = new LinkedList(); // don't want to do this...


List ll = new LinkedList();
ll.peekFirst(); // can't access peekFirst method
((DeQueue) ll).peekFirst(); // Kinda ugly

3 Answers 3

5
public interface Foo<T> extends List<T>, Deque<T>{}

public class Bar<T> extends LinkedList<T> implements Foo<T>{}

Foo ll = new Bar();

Don't have eclipse near me, this should compile though.

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

1 Comment

I knew there was a reason why Go's duck-typing style of interfaces was very appealing.
1

I think in Java you have no choice but to use the concrete type, or store two references to the same object, one typed as List, and the other as Dequeue.

List<T>       list;
Dequeue<T>    queue;

/** Construct a new instance of SomeClass */
private SomeClass() {
    LinkedList<T> tmp=new LinkedList<T>();
    list=tmp;
    queue=tmp;
    }

Not saying I especially like that, though.

Comments

0

I don't see how you can do that if you are declaring ll as a java.util.List. Should be able to create your own class but then you'll be tied to that and not to the stock classes/interfaces...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.