Incompatible Types Error in Java

强颜欢笑 提交于 2019-12-02 07:15: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.

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!