Incompatible Types Error in Java

后端 未结 2 797
故里飘歌
故里飘歌 2021-01-23 14:24

I keep receiving an error that says that there are incompatible types. I copied this directly out of a book because we are supposed to make changes to the code to enhance the ga

相关标签:
2条回答
  • 2021-01-23 14:35

    Change Object to E as the push() method's parameter type.

    public void push(E target) {
        if (isFull()) {
            stretch();
        }
        data[size] = target;
        size++;
    }
    

    Likewise, you should also change the declare return type of pop() and peek() to E.

    public E pop() {
        if (isEmpty()) {
            throw new EmptyStructureException();
        }
        size--;
        return data[size];
    }
    
    public E peek() {
        if (isEmpty()) {
            throw new EmptyStructureException();
        }
        return data[size - 1];
    }
    

    Now your class is fully generic.

    0 讨论(0)
  • 2021-01-23 15:00

    push method is not generic like the rest of the class, change it to:

    public void push(E target) {
        if (isFull()) {
            stretch();
        }
        data[size] = target;
        size++;
    }
    

    In any case the JDK ships with the class ArrayDeque which fulfill your requirements without being a piece o code pasted from a book.

    ArrayDeque<YourObj> stack = new ArrayDeque<YourObj>();
    stack.push(new YourObj());
    YourObj head = stack.peek();
    head = stack.pop();
    
    0 讨论(0)
提交回复
热议问题