【问题标题】:Custom LinkedList vs official LinkedList自定义 LinkedList 与官方 LinkedList
【发布时间】:2018-02-05 22:55:33
【问题描述】:

出于学习目的,我正在伪重新实现官方 Java 数据结构,我不太清楚为什么官方 LinkedList 在调试时看起来像一个数组,而我的看起来像链节点。

可能只是调试格式还是我完全错过了 - 理解 LinkedList 的实际实现方式?

自定义节点:

package Ch02_LinkedList;

public class CustomNode {
    private int data;

    CustomNode next = null;

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

自定义链接列表:

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.");
    }
}

输出:

【问题讨论】:

  • 查看(open-JDK)LinkedList ...它真的不是基于数组的! ...但也许你的 IDE/调试器是罪魁祸首!?? ;) 它是什么 - 智能? ...您是否尝试过实施 java.util.List ...?

标签: java debugging data-structures singly-linked-list


【解决方案1】:

IntelliJ 在Preferences 对话框中有一个选项:

为 Collection 类启用替代视图
选择此选项以更方便的格式显示集合和地图。

“数组”视图更方便查看LinkedList 的内容,你不觉得吗?

如果您不喜欢方便的格式,请将其关闭。

如果您的 CustomLinkedList 实现了 Collection,您甚至可能在调试器中获得同样方便的格式,尽管这只是我的猜测,因为我不使用 IntelliJ。

【讨论】:

  • 完美的安德烈亚斯。我关闭了该选项,现在我看到了结构。很高兴知道我的 Java 并不完全烂哈哈。 7 年后离开 PHP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
相关资源
最近更新 更多