I was reading about Collections, when this question stuck me.
Following is the code I wrote to test my doubt.
public static void main(String[] args) {
TreeMap<Integer, String> tree = new TreeMap<Integer, String>();
tree.put(1, "1");
tree.put(2, "2");
Set<Integer> set = tree.keySet();
System.out.println(set instanceof Set);
System.out.println(set instanceof HashSet);
}
Result :
true
false
Above code says that my set object is a instance of Set. but Set is an Interface how can it be instantiated. I’m confused. 🙁
Setis an interface, so no, you cannot directly instantiate it. Interfaces would be pretty useless if you couldn’t have an instance of one, though! The instance returned bytree.keySet()is some concrete implementation of theSetinterface.Let’s get super-specific, and look at the
TreeMap#keySet()source code:Okay, that doesn’t tell us much. We need to drill down:
So the concrete type returned is a
KeySet! There’s your implementation of theSetinterface. http://www.docjar.com/html/api/java/util/TreeMap.java.html#1021Which explains this:
Setis an interface;HashSetis an implementation of that interface.foo instanceof Setwill betruefor every instancefooof anySetimplementation. We already established that the concrete type of the object returned byTreeMap#keySet()is aKeySet, not aHashSet, so that explains whyset instanceof HashSetisfalse– becausesetis aKeySet, so it cannot be aHashSet!If that still doesn’t make sense to you, read up on
instanceof: