【发布时间】:2020-04-15 18:43:48
【问题描述】:
尝试使用自定义链表编写自定义(但众所周知的)堆栈通用实现。但算法不是重点。我的问题是,为什么不需要参数化
class Node<T>
以及声明
Node <T> top; //pointer to next node
会不会是多余的?为什么?或者可能需要使用另一个字符,例如<U>?
public class Stack<T> {
//T is the type parameter
Node top; //topmost element of stack
//defines each node of stack
class Node{
T value; //value of each node
Node next; //pointer to next node
public Node(T value){
this.value=value; //initializing
next=null;
}
}
//This function pushes new element
public void push(T value){
Node current=new Node(value);
if(isEmpty())
top=current; //if empty stack
else{
current.next=top;
top=current;
}
}
//This function pops topmost element
public T pop(){
T value=null;
if(!isEmpty()){
top=top.next;
value=top.value;
}
return value; //returning popped value
}
【问题讨论】:
-
因为它是一个非静态类,它可以访问封闭类的
T。如果您要拥有Node<T>,那么Node的T将是不同T与Stack<T>关联的Stack<T>(即内部类'T将隐藏外部类'T)。
标签: java generics inner-classes