Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>Set</code> is 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 by <code>tree.keySet()</code> is some concrete <em>implementation</em> of the <code>Set</code> interface.</p> <p>Let's get super-specific, and look at <a href="http://www.docjar.com/html/api/java/util/TreeMap.java.html#791" rel="nofollow">the <code>TreeMap#keySet()</code> source code</a>:</p> <pre><code>public Set&lt;K&gt; keySet() { return navigableKeySet(); } </code></pre> <p>Okay, that doesn't tell us much. We need to drill down:</p> <pre><code>public NavigableSet&lt;K&gt; navigableKeySet() { KeySet&lt;K&gt; nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = new KeySet(this)); } </code></pre> <p>So the concrete type returned is a <code>KeySet</code>! There's your implementation of the <code>Set</code> interface. <a href="http://www.docjar.com/html/api/java/util/TreeMap.java.html#1021" rel="nofollow">http://www.docjar.com/html/api/java/util/TreeMap.java.html#1021</a></p> <p>Which explains this:</p> <pre><code>System.out.println(set instanceof Set); // prints true System.out.println(set instanceof HashSet); // prints false </code></pre> <p><code>Set</code> is an interface; <code>HashSet</code> is an implementation of that interface. <code>foo instanceof Set</code> will be <code>true</code> for every instance <code>foo</code> of <em>any</em> <code>Set</code> implementation. We already established that the concrete type of the object returned by <code>TreeMap#keySet()</code> is a <code>KeySet</code>, not a <code>HashSet</code>, so that explains why <code>set instanceof HashSet</code> is <code>false</code> – because <code>set</code> is a <code>KeySet</code>, so it cannot be a <code>HashSet</code>!</p> <p>If that still doesn't make sense to you, <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html" rel="nofollow">read up on <code>instanceof</code></a>:</p> <blockquote> <p>The <code>instanceof</code> operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload