gpt4 book ai didi

java - "key==this"的情况可能吗?

转载 作者:行者123 更新时间:2023-11-29 03:31:42 27 4
gpt4 key购买 nike

我正在阅读哈希表的代码。我对 toString() 方法感到困惑,代码是这样的:

public synchronized String toString() 
{
int max = size() - 1;
if (max == -1)
return "{}";

StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<K,V>> it = entrySet().iterator();
sb.append('{');

for (int i = 0; ; i++)
{
Map.Entry<K,V> e = it.next();
K key = e.getKey();
V value = e.getValue();

// Is "key == this" possible ? What the "this" stands for ?
sb.append(key == this ? "(this Map)" : key.toString());
sb.append('=');
sb.append(value == this ? "(this Map)" : value.toString());

if (i == max)
return sb.append('}').toString();

sb.append(", ");
}
}

所以,如果代码不检查"key equals this"与否,也许toString() 方法会死循环?

最佳答案

当然可以:

Hashtable table = new Hashtable();
table.put(table, table);
System.out.println("table = " + table);

输出:

table = {(this Map)=(this Map)}

但是请注意,这种映射的行为可能会令人惊讶(因为它的哈希码和等号会发生变化)。例如,在下面的示例中,一旦您添加了另一个条目,您就无法从 map 本身中删除它:

Hashtable table = new Hashtable();
table.put(table, table);
System.out.println("table = " + table);
table.put("abc", "def");
System.out.println("table = " + table);
table.remove(table); //does not work as expected !!!
System.out.println("table = " + table);

输出:

table = {(this Map)=(this Map)}
table = {abc=def, (this Map)=(this Map)}
table = {abc=def, (this Map)=(this Map)}

关于java - "key==this"的情况可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com