Incompatible Types Error in Java

2019-03-04 06:20发布

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 game of War. I have all of the other classes complete and compiled but this one is giving me fits. Here is the code:

public class ArrayStack<E> implements Stack<E> {

private E[] data;

private int size;

public ArrayStack() {
    data = (E[])(new Object[1]);
    size = 0;
}

public boolean isEmpty() {
    return size == 0;
}

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

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

protected boolean isFull() {
    return size == data.length;
}

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

protected void stretch() {
    E[] newData = (E[])(new Object[data.length * 2]);
    for (int i = 0; i < data.length; i++) {
        newData[i] = data[i];
    }
    data = newData;
}   
}

The error is occurring in the push() method at the data[size] = target; line.

EDIT::: I'm now receiving this error. "type Stack does not take parameters public class ArrayStack implements Stack"

The stack class is as follows.

public interface Stack<E> {

public boolean isEmpty();

public E peek();

public E pop();

public void push(E target);

}

2条回答
在下西门庆
2楼-- · 2019-03-04 06: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.

查看更多
\"骚年 ilove
3楼-- · 2019-03-04 06:43

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();
查看更多
登录 后发表回答