问题
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?
回答1:
Of course it is possible:
Hashtable table = new Hashtable();
table.put(table, table);
System.out.println("table = " + table);
outputs:
table = {(this Map)=(this Map)}
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:
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);
outputs:
table = {(this Map)=(this Map)}
table = {abc=def, (this Map)=(this Map)}
table = {abc=def, (this Map)=(this Map)}
回答2:
This is so that if you put the HashTable into itself you don't get an infinite loop. Consider:
final Map map = new Hashtable();
map.put(map, "test");
回答3:
// Is "key == this" possible ? What the "this" stands for ?
'this keyword' refers to the current instance of the object. "key == this" checks if key refers to the current insatnce of the object.
回答4:
Yes it is. This
HashTable<Object, Object> maptest = new HashTable<Object, Object>();
mapTest.put(mapTest, 1);
would have key == this return true
回答5:
There is a possibility that keeping a map as key in same map.
HashMap<Object, Object> selfmap = new HashMap<Object, Object>();
selfmap.put(selfmap, selfmap);
回答6:
if the key and this object (HashTable as you say) reference equals then the condition key == this is true
来源:https://stackoverflow.com/questions/17835592/is-the-situation-of-key-this-possible