完全卡在这个错误上。这是错误来自的类。
/** An array-based Stack. */
public class ArrayStack<E> implements Stack {
/** Array of items in this Stack. */
private E[] data;
/** Number of items currently in this Stack. */
private int size;
/** The Stack is initially empty. */
public ArrayStack() {
data = (E[])(new Object[1]); // This causes a compiler warning
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];
}
/** Return true if data is full. */
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
/** Double the length of data. */
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]); // Warning
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
这里是 Stack 类,以备不时之需:
/** A last-in, first-out stack. */
public interface Stack<E> {
/** Return true if this Stack is empty. */
public boolean isEmpty();
/**
* Return the top item on this Stack, but do not modify the Stack.
* @throws EmptyStructureException if this Stack is empty.
*/
public E peek();
/**
* Remove and return the top item on this Stack.
* @throws EmptyStructureException if this Stack is empty.
*/
public E pop();
/** Add target to the top of the Stack. */
public void push(E target);
}
错误与 ArrayStack 类中 push(Object target) 方法中的 data[size] = target;
行有关。
最佳答案
data[size] = target;
1) 这里 data
指E array
和 target
指Object
.
泛型带来类型安全。所以你不能从 Object 转换为 E。
2) public class ArrayStack<E> implements Stack {
不正确,因为您没有为正在实现的接口(interface)提供参数化类型。
写作 public class ArrayStack<E> implements Stack<E> {
会更安全,并会迫使您实现 Stack
通过尊重 Stack
中使用的参数化类型的方法方法。
例如:public void push(E target);
3) 符合ArrayStack
中声明的参数化类型你应该在你的方法中使用参数化类型而不是 Object
.
所以你应该替换
public void push(Object target) {
由
public void push(E target) {
并且您应该在声明为声明类型 Object
的所有方法中做同样的事情。而不是 E
.例如:
public Object peek()
和
public Object pop() {
关于java - 错误 : incompatible types: java. lang.Object 无法转换为 E,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42242593/