[英]Lost java object identity after creating my own toString method
assume I have my own linkedlist implementation: 假设我有自己的链表实现:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
When I have this simple setup, I can use a node in a Map: 当我有这个简单的设置时,我可以在Map中使用一个节点:
ListNode A = new ListNode(1);
ListNode B = new ListNode(2);
ListNode C = new ListNode(3);
A.next = B;
B.next = C;
Map<ListNode, Integer> hmp = new HashMap<>(Map.ofEntries(
Map.entry(A, 1)
));
When I print the Map object, I got: 当我打印Map对象时,我得到了:
System.out.println(hmp);
// >>> {ListNode@57829d67=1}
However, after I implement a toString method for my linkedlist, so that I can print it out straightforwardly: 但是,在为我的链表实现toString方法之后,我可以直接打印出来:
public String toString() {
if (this.next != null) {
return this.val + "->" + this.next.showString();
} else {
return String.valueOf(A.val);
}
}
Now If I can print the linked list nicely, but if I print the Map again: 现在如果我可以很好地打印链表,但是如果我再次打印地图:
System.out.println(A);
// >>> 1->2->3
System.out.println(hmp);
// >>> {1->2->3=1}
You can see that I lost the original way of showing the identity of the ListNode
object in map. 您可以看到我丢失了在地图中显示
ListNode
对象标识的原始方式。
ListNode@57829d67
? ListNode@57829d67
? The only that I can see is not to override the toString method but create a different method to show the string of my linkedlist object. 我唯一能看到的不是覆盖toString方法,而是创建一个不同的方法来显示我的linkedlist对象的字符串。 I am not sure if this is a good idea
我不确定这是不是一个好主意
Thanks 谢谢
That is not an "identity"; 那不是 “身份”; it is the
hashCode()
of your ListNode
. 它是
ListNode
的hashCode()
。 Call hashCode()
to get the "57829d67" whenever you want. 调用
hashCode()
可以随时获取“57829d67”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.