我正在阅读哈希表的代码。我对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 是否等于 this”,也许 toString() 方法可以是无限循环?