简体   繁体   English

如何将ArrayList转换为接口?

[英]How do I convert ArrayList to interface?

The following code is giving me the error "Type mismatch: cannot convert from ArrayList to StackInterface". 下面的代码给我错误“类型不匹配:无法从ArrayList转换为StackInterface”。 How would I convert or am I using the incorrect data type for ArrayList? 我该如何转换或为ArrayList使用错误的数据类型?

public class PostFixStack<T> implements StackInterface<T>
    protected ArrayList<T> elements; // ArrayList that holds stack elements
    public PostFixStack() {elements = new ArrayList<T>();      
}

public int evaluate(String expression){
    Scanner tokenizer = new Scanner(expression);
    StackInterface<Integer> stack = new ArrayList<T>();

The answer is: you don't. 答案是:您不知道。

When you turn to the javadoc for ArrayList, you find there: 当您转向ArrayList的javadoc时 ,会发现:

All Implemented Interfaces: 所有已实现的接口:

Serializable, Cloneable, Iterable, Collection, List, RandomAccess 可序列化,可克隆,可迭代,集合,列表,RandomAccess

StackInterface isn't there. StackInterface不存在。 Thus an ArrayList can never be casted to that type. 因此,ArrayList 永远不能转换为该类型。

Thus, you would rather need: 因此,您宁愿需要:

StackInterface<Integer> stack = new PostFixStack<>();

In other words: the fact that your stack implementation class uses an ArrayList is an internal detail of that implementation, and when you want to create one of your stacks, then you instantiate that implementation, and not something else! 换句话说:您的堆栈实现类使用ArrayList的事实是该实现的内部细节,并且当您要创建一个堆栈时,您可以实例化实现,而不是其他实例!

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

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