java - 为什么不需要使用泛型内部类进行参数化?
问题描述
尝试使用自定义链表编写自定义(但众所周知的)堆栈通用实现。但算法不是重点。我的问题是,为什么不需要参数化
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
}
解决方案
请注意,Node
这里的类不是static
. 这意味着每个实例都有Stack
自己的Node
类。像任何其他成员一样,它可以访问其封闭类' T
。
推荐阅读
- protocol-buffers - 将 WCF 服务迁移到 gRPC 服务时出错
- reactjs - React-beautiful-dnd 平面数据结构到嵌套
- python - 如果某个值连续出现至少一次,则更改pandas中该行的最后一个值
- python - 在 pandas 中使用半小时增量计算 8 小时大小的滚动窗口
- python - 使数组的所有元素都相同
- android - Flutter Bloc - BlocListener 对状态变化没有反应
- reactjs - 此表达式不可调用。并非所有类型为 'string | ((searchTerm: string) => 承诺
) | []' 是可调用的 - python - 为什么花哨的索引与 numpy 中的切片不同?
- sql - SQL 查询未对临时表中的所有记录执行
- delphi - 在 Delphi 中同时使用 OR 和 AND 条件进入 AdoTable 过滤器