【发布时间】:2015-03-30 15:16:42
【问题描述】:
我从一本书中获得了以下代码,用于实现单链表。我不明白removeFirst() 方法中的一些代码行,它从LinkedList 中删除了第一个节点。
class ListNode{
private String element;
private ListNode next;
public ListNode(){
element = null;
next = null;
}
public ListNode(String s, ListNode n){
element = s;
next = n;
}
//Access method
public String getElement(){
return element;
}
public ListNode getNext(){
return next;
}
//Modify method
public void setNext(ListNode n){
next = n;
}
}
public String removeFirst(){
if(head == null)
return null;
else{
ListNode temp = head;
head = head.getNext();
temp.setNext(null); //Which I don't understand, is it necessary?
size --;
return temp.getElement();
}
}
看来temp.setNext(null);这个语句可以省略。那么为什么会出现在这里,和java中的垃圾回收有什么关系吗?由于我是 Java 新手,有什么建议或想法吗?
【问题讨论】:
-
因为列表是双向链表。我猜 head.previous 在删除第一个元素后应该为 null。
-
列表为单链表。
-
正如@Thinkingcaps 评论中的答案所说:迭代器保留对 ListNodes 的引用。
-
针对@keuleJ 的评论,我编辑了我的答案。这条线是必要的。
标签: java garbage-collection adt