Is a "key" situation possible?

I am reading the Hashtable code. and I got confused in the toString() method, the code looks 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 does not check whether the "key is equal to this" or not, maybe the toString () method could be an infinite loop?

+1
source share
6 answers

Of course it is possible:

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

outputs:

 table = {(this Map)=(this Map)} 

Please note, however, that the behavior of such a card may be unexpected (since its hash code will change and equal). For example, in the example below, you cannot remove the card from yourself after adding another record:

 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)} 
+3
source

This is so that if you put a HashTable in yourself, you will not get an infinite loop. Consider:

 final Map map = new Hashtable(); map.put(map, "test"); 
+1
source
  // Is "key == this" possible ? What the "this" stands for ? 

'this keyword' refers to the current instance of the object. "key == this" checks if the key refers to the current insatnce of the object.

0
source

Yes it is. it

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

would have key == this return true

0
source

It is possible to save the map key in the same map .

 HashMap<Object, Object> selfmap = new HashMap<Object, Object>(); selfmap.put(selfmap, selfmap); 
0
source

if the key object and this object (the HashTable link, as you say) is equal then the condition key == this is true

0
source

Source: https://habr.com/ru/post/1493335/


All Articles