简体   繁体   English

为什么输入<K,V>中需要输入参数<K,V>?

[英]Why type parameter <K,V> required in Entry<K,V>?

In java.util.Map (as shown below), type parameters <K, V> of Entry are over shadowing type parameters <K, V> of Map . java.util.Map (如下所示),类型参数<K, V>Entry超过遮蔽类型参数<K, V>Map

interface Map<K,V> {
      ......
      interface Entry<K,V> {
           .....
      }
}

class DblyLinkList from here has following innerclass DListNode that does not require overshadowing type parameter T . 来自这里的 class DblyLinkList具有以下内部类DListNode ,其不需要遮蔽类型参数T

public class DblyLinkList<T> implements Iterable<T> {
     .......
     class DListNode {
          private T item;
        private DListNode prev;
        private DListNode next;

        DListNode(T item, DListNode p, DListNode n) {
            this.item = item;
            this.prev = p;
            this.next = n;
        }
      }
      ......
}

Can you please help me understand the reason for overshadowing type parameters of Map ? 你能帮我理解为Map类型参数蒙上阴影的原因吗?

Interfaces defined inside a class or interface are static, which means they don't have access to the generic parameters of their parent class. 在类或接口内定义的接口是静态的,这意味着它们无法访问其父类的泛型参数。 So Entry needs the K and V from its parent. 因此, Entry需要来自其父级的KV

In contrast, the DListNode is an inner-class of DblyLinkList<T> and so does have access to the generic type T - it actually contains a reference back to its containing class too. 相比之下, DListNodeDblyLinkList<T>的内部类,因此可以访问泛型类型T - 它实际上也包含一个返回其包含类的引用。

Note, if the DListNode was defined as static class (which is how I would define it), it would no longer be an inner class and so not have access to its parents generic parameters - and so would need to be DListNode<K,V> too. 注意,如果DListNode被定义为static class (我将如何定义它),它将不再是内部类,因此无法访问其父类通用参数 - 因此需要DListNode<K,V>也是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM