首页 > 解决方案 > 为什么不需要使用泛型内部类进行参数化?

问题描述

尝试使用自定义链表编写自定义(但众所周知的)堆栈通用实现。但算法不是重点。我的问题是,为什么不需要参数化

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
        }

标签: javagenericsinner-classes

解决方案


请注意,Node这里的类不是static. 这意味着每个实例都有Stack自己的Node类。像任何其他成员一样,它可以访问其封闭类' T


推荐阅读