在空的 LinkedList 中存储一个字符串值
public class LinkedListExplained {
public Node head;
public Node tail;
public int size;
public LinkedListExplained() { // Constructor
head = null;
tail = null;
size = 0;
}
public class Node{ // Inner Class
String value;
Node next;
}
public void add(String value){
Node node = new Node();
node.value = value;
size++;
if (head == null){
head = node;
tail = node;
return;
}
tail.next = node;
tail = node;
}
问题,当将单个 String 值存储到空 LinkedList 时,它是否会存储相同的值两次? 一次是头,一次是尾?
public class LinkedListExplained {
public Node head;
public Node tail;
public int size;
public LinkedListExplained() { // Constructor
head = null;
tail = null;
size = 0;
}
public class Node{ // Inner Class
String value;
Node next;
}
public void add(String value){
Node node = new Node();
node.value = value;
size++;
if (head == null){
head = node;
tail = node;
return;
}
tail.next = node;
tail = node;
}
Question, when storing a single String value to an empty LinkedList, does it store the same value twice?
Once as head and once as tail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不会。
head
和tail
变量指向同一个Node
对象。该对象包含一次String
。No. The
head
andtail
variables point to the sameNode
object. That object contains theString
once.如果你正在学习 Java,你首先需要了解的是,在 Java 中,所有看起来像对象的东西实际上都不是对象;相反,它是一个对象。它是一个指向对象的指针。当然,两个指针可能指向同一个对象。
因此,语句
public Node head;
并未声明Node
的实例。它声明了一个指向 Node 实例的指针。这就是为什么你必须稍后使用 new Node(); 的原因。因此,由于您将
head
和tail
指针都设置为指向Node
的同一个实例,因此您可能有两个副本那个节点,但事实上你没有。您只有一个Node
实例,并且有两个指向它的指针。If you are learning Java, the first and foremost thing you need to understand is that in Java, everything that looks like an object is never actually an object; it is a pointer to an object. And of course two pointers may point to the same object.
So, the statement
public Node head;
does not declare an instance ofNode
. It declares a pointer to an instance ofNode
. That's why you have to usenew Node();
later.So, since you set both the
head
and thetail
pointers to point to the same instance ofNode
, it might appear that you have two copies of that node, but in fact you do not. You only have one instance ofNode
, and you have two pointers pointing at it.