簡體   English   中英

鏈表中的 JAVA 類型參數

[英]JAVA Type Parameter in Linked List

Java 類型參數聲明作為內部 class 的一部分。

我的問題在鏈表上。 我在ArrayList實現中看到了同樣的情況。

public class LinkedList<E> implements Iterable<E> {....

private class LinkedIterator implements Iterator<E>{...} //inner class of LinkedList

private static class ListNode<E> //implemented as nested static class

Question: Why does the iterator (and constructor for LinkedList) both do not require type parameter, I think listNode requires because static class make it can not access class header of the outter class.

任何 class 定義是:

  • 在另一個 class 定義中。
  • 標記static

是一個內部 class。 從概念上講,class 僅存在於外部 class 的單個實例中。 實際上,這意味着:

  • 外部類型有一個隱藏的、私有的和最終的字段。 所有的構造函數都需要一個外部實例,但是 java 語法是特殊的: outerRef.new Inner(); - 如果您處於Outer.this合理的上下文中,則這是默認值。 該字段沒有吸氣劑。

  • 外部 class 的所有類型參數在內部 class 中也可用,除非有陰影。

因此,鑒於private class LinkedIteratorclass LinkedList內部,它就是這種內部 class,它具有隱藏字段<E>來自LinkedList<E> 然而,節點是static ,因此它沒有該字段並且不繼承<E> - 而是選擇自己聲明它。

請注意,內部類既復雜又令人驚訝。 例如,它們可能會弄亂垃圾收集(因為它們持有對其外部的引用;例如,這將阻止外部的 gc)。 作為一般規則,如果您不確定,強烈推薦 static 內部類,使外部實例或其 generics 的任何 inheritance 顯式。

換句話說:

public class Outer<E> {
    public class Inner {}
}

很棘手; 不要這樣做,除非您確定內部 class 的概念完全適用。 如果您不知道這意味着什么或不確定,請改寫為:

public class Outer<E> {
    public static class Inner<E> {
        private final Outer<E> context;

        public Inner(Outer<E> context) {
            this.context = context;
        }
    }
}

當然,省略所有不需要的部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM