1

我正在阅读哈希表的代码。我对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() 方法可以是无限循环?

4

6 回答 6

3

当然有可能:

Hashtable table = new Hashtable();
table.put(table, table);
System.out.println("table = " + table);

输出:

table = {(this Map)=(this 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)}
于 2013-07-24T13:37:23.493 回答
1

这样一来,如果您将其HashTable放入自身,就不会出现无限循环。考虑:

final Map map = new Hashtable();
map.put(map, "test");
于 2013-07-24T13:37:48.760 回答
0
    // Is "key == this" possible ? What the "this" stands for ?

“this 关键字”指的是对象的当前实例。"key == this" 检查 key 是否引用对象的当前实例。

于 2013-07-24T13:37:13.570 回答
0

是的。这

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

会有key == this回报true

于 2013-07-24T13:37:52.073 回答
0

有可能保持 a mapas 键相同map

HashMap<Object, Object> selfmap = new HashMap<Object, Object>();
selfmap.put(selfmap, selfmap);
于 2013-07-24T13:38:02.837 回答
0

如果keyandthis对象(如您所说的 HashTable)引用等于,则条件key == thistrue

于 2013-07-24T13:38:12.780 回答