How do I convert ArrayList to interface?

Franklin :

The following code is giving me the error "Type mismatch: cannot convert from ArrayList to StackInterface". How would I convert or am I using the incorrect data type for 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>();
GhostCat salutes Monica C. :

The answer is: you don't.

When you turn to the javadoc for ArrayList, you find there:

All Implemented Interfaces:

Serializable, Cloneable, Iterable, Collection, List, RandomAccess

StackInterface isn't there. Thus an ArrayList can never be casted to that type.

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!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99201&siteId=1