简体   繁体   English

同时需要List和DeQueue方法时,在Java中使用LinkedList

[英]Using LinkedList in java, when needing both List and DeQueue methods

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? 如果我要实例化LinkedList并要求访问List和Dequeue接口中的方法,并且不想键入具体的实现,并且不想在接口之间进行强制转换,是否有办法?

ie: 即:

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
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. 我附近没有日食,不过应该编译。

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. 我认为在Java中您别无选择,只能使用具体类型,或者存储对同一对象的两个引用,一个引用键入List,另一个引用作为出队。

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. 不过,并不是说我特别喜欢那样。

I don't see how you can do that if you are declaring ll as a java.util.List. 如果您将ll声明为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... 应该能够创建自己的类,但是您将被绑定到该类而不是库存类/接口...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM