簡體   English   中英

自定義LinkedList與官方LinkedList

[英]Custom LinkedList vs official LinkedList

我出於學習目的而偽偽地重新實現了正式的Java數據結構,但我不確定為什么調試時正式的LinkedList看起來像一個數組,而我的看起來像是鏈結節點。

它可能只是調試格式,還是我完全錯過了LinkedList實際實現方式的理解?

CustomNode:

package Ch02_LinkedList;

public class CustomNode {
    private int data;

    CustomNode next = null;

    CustomNode(int data) {
        this.data = data;
    }
}

CustomLinkedList:

package Ch02_LinkedList;

import java.util.LinkedList;

/**
 * Custom implementation of a singly linked list.
 *
 * A double linked list would also contain a "prev" node.
 */
public class CustomLinkedList {
    private CustomNode head;

    public void add(int value) {
        if (this.head == null) {
            this.head = new CustomNode(value);

            return;
        }

        CustomNode current = this.head;

        while (current.next != null) {
            current = current.next;
        }

        current.next = new CustomNode(value);
    }

    public void prepend(int value) {
        CustomNode newHead = new CustomNode(value);
        newHead.next = this.head;
        this.head = newHead;
    }

    public void remove(int index) throws IllegalArgumentException {
        if (this.head == null) {
            return;
        }

        if (index == 0) {
            this.head = head.next;

            return;
        }

        CustomNode current = head;
        int currentIndex = 0;

        while (current.next != null) {
            if (index == currentIndex+1) {
                current.next = current.next.next;

                return;
            }

            current = current.next;
            currentIndex++;
        }

        throw new IllegalArgumentException("No such a index has been found.");
    }

    public static void main(String[] args) {
        CustomLinkedList myList = new CustomLinkedList();
        myList.add(10);
        myList.add(20);
        myList.add(30);
        myList.add(40);
        myList.add(50);
        myList.add(60);
        myList.remove(4);

        LinkedList<Integer> officialList = new LinkedList<>();
        officialList.add(10);
        officialList.add(20);
        officialList.add(30);
        officialList.add(40);
        officialList.add(50);
        officialList.add(60);
        officialList.remove(4);

        System.out.println("Done.");
    }
}

輸出:

在此處輸入圖片說明

IntelliJ在“ 首選項”對話框中有一個選項:

為集合類啟用替代視圖
選擇此選項以更方便的格式顯示收藏和地圖。

“數組”視圖對於查看LinkedList內容更方便,您認為嗎?

如果您不喜歡方便的格式,請將其關閉。

如果您的CustomLinkedList實現了Collection ,那么您甚至可以在調試器中獲得相同的便捷格式,盡管這只是我的猜測,因為我不使用IntelliJ。

暫無
暫無

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

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