我不断收到一条错误,指出存在不兼容的类型。我直接从书中复制了这段代码,因为我们应该对代码进行更改以增强 War 游戏。我已经完成并编译了所有其他类(class),但这个类(class)让我感到不舒服。这是代码:
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;
}
}
错误发生在 data[size] = target 处的 push() 方法中;线。
编辑::: 我现在收到此错误。 “类型 Stack 不带参数 公共(public)类 ArrayStack 实现 Stack”
堆栈类如下。
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
最佳答案
将 Object
更改为 E
作为 push()
方法的参数类型。
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
同样,您还应该将 pop()
和 peek()
的声明返回类型更改为 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];
}
现在你的类是完全通用的。
关于java - Java 中的不兼容类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284703/