In HashMap
class there is an inner class KeySet
whose instance is returned by the HashMap
's instance method keySet()
. This inner class contains the following method.
public void clear() {
HashMap.this.clear();
}
I understand the general semantics of "this
"
The above style of using "this
" seems interesting,
Given the above two it should be possible to have a static reference to any dynamically created instance object but that's not possible since there could be infinite number of instances at runtime and there aren’t any language constructs to specify this relation between a class and its instances.
I am definitely missing something, can someone help me understand this better.
HashMap. clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap. Parameters: The method does not accept any parameters. Return Value: The method does not return any value.
clear() method is used to remove all the elements from a Set. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing Set. Return Value: The method does not returns any value.
We can remove entries from HashMap using remove(key) or clear() methods. remove method removes the mapping for the key specified in the parameter while clear() method removes all the entries from the HashMap and returns void.
If all you want to do is discard the data in the Map , then you need not (and in fact should not) call clear() on it, but simply clear all references to the Map itself, in which case it will be garbage collected eventually. Show activity on this post. Looking at the source code, it does look like HashMap never shrinks.
When a non-static inner class is created, it gets a reference to its enclosing class instance. In order to reference that instance, a special syntax is used: the keyword this
is prefixed with the name of the enclosing class. When used without a class name prefix, this
keyword refers to the instance of the inner class itself.
Essentially, the call is made to the clear
method of the HashMap
class. Note that since the method of the inner class is called clear
as well, the call without HashMap.this
would have been directed to the clear()
inside the inner class, causing infinite recursion.
As correctly stated by Roger Lindsjö in a comment below Technically the idiom is known as qualified this construct. (JLS 15.8.4)
HashMap.this.clear();
calls the current instance of HashMap
, you mentioned that its calling from a InnerClass, so that's how its referencing the Outter class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With