Is the situation of “key==this” possible?

2019-08-04 00:02发布

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?

6条回答
我想做一个坏孩纸
2楼-- · 2019-08-04 00:13

if the key and this object (HashTable as you say) reference equals then the condition key == this is true

查看更多
我想做一个坏孩纸
3楼-- · 2019-08-04 00:31

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);
查看更多
别忘想泡老子
4楼-- · 2019-08-04 00:32

Yes it is. This

HashTable<Object, Object> maptest = new HashTable<Object, Object>();
mapTest.put(mapTest, 1);

would have key == this return true

查看更多
Rolldiameter
5楼-- · 2019-08-04 00:38

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");
查看更多
Deceive 欺骗
6楼-- · 2019-08-04 00:38
    // 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.

查看更多
你好瞎i
7楼-- · 2019-08-04 00:39

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)}
查看更多
登录 后发表回答