为什么不需要使用通用内部类进行参数化?

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

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
        }
bajo42 回答:为什么不需要使用通用内部类进行参数化?

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

,
  

会多余吗?

是的

  

为什么?

由于Node被声明为Stack的内部类,因此变量TNode的范围内,可以根据需要使用。

  

或者可能需要使用其他字符,例如<U>

如果需要声明一个不同的类型变量,则可以这样做。 (实际上,您可能应该使用其他变量名称。)它可能看起来像这样:

public class Stack<T> {

    Node<T> top;                               // CHANGE HERE

     class Node<U> {                           // CHANGE HERE
        U value;                               // CHANGE HERE
        Node<U> next;                          // CHANGE HERE

        public Node(U value) {                 // CHANGE HERE
            this.value = value;
            next = null;
        }
    }

    public void push(T value) {
        Node<T> current = new Node<>(value);   // CHANGE HERE
        if (isEmpty())
            top = current;
        else {
            current.next = top;
            top = current;
        }
    }

    public T pop() {
        T value = null;
        if (!isEmpty()) {
            top = top.next;
            value = top.value;
        }
        return value;
    }

这说明添加额外的类型变量会导致更多的代码,并且不会提高可读性。

,

如果您的Node类是其自己的顶级类(在其自己的.java文件中),则它将需要一个通用参数,如您期望的那样。我建议您这样做。

但是,因为它是Stack的(非静态)内部类,所以它可以访问Stack instance 中的所有内容,包括所有通用信息。

本文链接:https://www.f2er.com/2865275.html

大家都在问