我为了学习目的而伪重新实现官方Java数据结构,并且我不太清楚为什么官方LinkedList看起来像一个数组而我的那个在调试时看起来像链式节点。
它可能只是调试格式还是我完全错过了LinkList实际实现的方式?
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.");
}
}
输出:
答案 0 :(得分:4)
IntelliJ在Preferences对话框中有一个选项:
为集合类启用备用视图
选择此选项可以更方便的格式显示集合和地图。
&#34;数组&#34;查看LinkedList
的内容更方便,您认为不是吗?
如果您不喜欢方便的格式,请将其关闭。
如果CustomLinkedList
已实施Collection
,您甚至可能会在调试器中获得相同的便捷格式,但这只是我的猜测,因为我不使用IntelliJ