java - 错误 : incompatible types: java. lang.Object 无法转换为 E

标签 java

完全卡在这个错误上。这是错误来自的类。

 /** 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) 这里 dataE arraytargetObject .
泛型带来类型安全。所以你不能从 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/

相关文章:

java - 如何仅在按住按钮时播放音频?

java - 在使用 Logback 记录计算数据时,我们应该使用 isDebugEnabled() 吗?

java - 在 Java 中获取文本大小(以字节为单位)的最佳方法是什么?

java - 反编译的代码导致 “Cannot reference a field before it is defined”

javascript - PageDown 通过 ScriptEngine 错误解析 Markdown

java - 如何获取一个字符来替换字符串中的部分(java)

java - JBoss 焊接 CDI : Inject the same instance in two different Objects

java - 如何暂停/继续计划任务?

java - JPA Spring 存储库日期过滤返回空数组

java - 为什么在添加回车时 stdout 解码失败?