我正在阅读哈希表的代码。我对 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/