java我得到这个错误:E不能转换成E。
对不起,我不知道如何清楚地表达我的问题。 我有一个堆栈,我想实现一个方法,通过使用RemovedUpplicates()方法删除E类型对象的所有重复项。 该方法调用类中名为removeAll()的另一个方法,该方法查找所有类型为E的对象,如果在堆栈中找到,则将其删除。 我知道问题是编译器无法判断E类型的KeepFile堆栈是否与原始堆栈中的E类型相同。 我再一次为令人困惑的语言道歉。但是有人能帮我找到解决办法吗
public class ArrayStack<E> implements Stack<E> {
//push() adds object to stack
//pop() removes object from stack
...
public E peek() { //returns object without removing from stack
if (isEmpty()) {
throw new EmptyStackException();
}
@SuppressWarnings("unchecked")
E result = (E) stack[size - 1];
return result;
}
public void removeAll(E obj){
ArrayStack<E> keepPile = new ArrayStack<>();
ArrayStack<E> throwAwayPile = new ArrayStack<>();
while(!this.isEmpty()){
if(obj.equals(this.peek())){
throwAwayPile.push(this.pop());
}else{
keepPile.push(this.pop());
}
}
while(!keepPile.isEmpty()){
this.push(keepPile.pop());
}
}
public static <E> void removeDuplicates(Stack<E> stack){
ArrayStack<E> keepPile = new ArrayStack<>();
while(!stack.isEmpty()){
keepPile.push(stack.pop());
removeAll(keepPile.peek()); //problem is thrown here. The types are not guaranteed to be the same
}
}
}
共 (0) 个答案