Pla*_*rth 2 java generics stack
这是我的代码:
package datastructures;
import java.util.Iterator;
public class Stack<T>{
private class Node<T>{
T data;
Node next;
}
private int size;
private Node head;
private Node newNode(T data){
Node new_node = new Node();
new_node.data = data;
new_node.next = null;
return new_node;
}
public Stack(){
size = 0;
head = null;
}
public T pop() {
if(head == null)
return null;
T ret_val = head.data; //Error here
head = head.next;
this.size--;
return ret_val;
}
}
Run Code Online (Sandbox Code Playgroud)
我在pop方法中收到错误,这是错误:
Error: incompatible types : java.lang.Object cannot be converted to T
Run Code Online (Sandbox Code Playgroud)
我不理解此错误,我不在代码中的任何地方使用对象。
当您将Node声明为
private class Node<T>
Run Code Online (Sandbox Code Playgroud)
您要声明一个通用类型,其中另一个T作为封闭类型中的T。您正在隐藏T。因此,简而言之,就好像您在声明它为
private class Node<E>
Run Code Online (Sandbox Code Playgroud)
只需使用
private class Node
Run Code Online (Sandbox Code Playgroud)