I'm reading the Hashtable's code. and I am confused about the toString()
method, the code is like this :
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(", ");
}
}
So,if the code doesn't check whether "key equals this" or not, maybe the toString() method can be endless loop?
if the
key
andthis
object (HashTable as you say) reference equals then the conditionkey == this
istrue
There is a possibility that keeping a
map
as key in samemap
.Yes it is. This
would have
key == this
returntrue
This is so that if you put the
HashTable
into itself you don't get an infinite loop. Consider:'this keyword' refers to the current instance of the object. "key == this" checks if key refers to the current insatnce of the object.
Of course it is possible:
outputs:
Note however that the behaviour of such a map could be surprising (as its hashcode and equals will change). For example, in the example below, you can't remove the map from itself once you add another entry:
outputs: