Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You've defined a type <code>Node&lt;E&gt;</code> which represents a node in a tree of E's. For example, <code>Node&lt;Integer&gt;</code> is a node in a tree of Integers, and <code>Node&lt;String&gt;</code> is a node in a tree of Strings.</p> <p>Now you want a variable <code>SOIL</code> that contains all the roots of these various trees of different types (hehe, <em>soil</em>, I get it now). Set aside the static field issue for now. What should the class of <code>SOIL</code> be? In other words, how do we declare and create the <code>SOIL</code> instance?</p> <pre><code>Node&lt;/*something1*/&gt; SOIL = new Node&lt;/*something2*/&gt;(null, null); </code></pre> <p>Since <code>SOIL</code> is going to have children that are <code>Node&lt;Integer&gt;</code> and <code>Node&lt;String&gt;</code> then it has to be something like <code>Node&lt;?&gt;</code> or <code>Node&lt;Object&gt;</code>. You can't instantiate an object using a wildcard type argument, so the best you can do is something like this:</p> <pre><code>Node&lt;?&gt; SOIL = new Node&lt;Object&gt;(null, null); </code></pre> <p>(If you use the Java 7 diamond construct <code>new Node&lt;&gt;(...)</code> it ends up using <code>Object</code> in this case anyway.)</p> <p>The problem is, this still doesn't work. The way the <code>Node&lt;E&gt;</code> type is defined is as a <strong>homogeneous</strong> tree of E's. But one subtree of <code>SOIL</code> is a tree of Integers and another subtree is a tree of Strings, so <code>SOIL</code> wants to be a <strong>heterogeneous</strong> tree. Therefore, <code>SOIL</code> cannot be a <code>Node&lt;E&gt;</code> for any <code>E</code>.</p> <p>At least, not in a type-safe fashion. You could write the code to do this, but you'd have to add some casts, and you'd get unchecked warnings. These warnings would tell you that this approach isn't working. For example, consider some code that takes a <code>Node&lt;E&gt;</code> and operates on all of its siblings (that is, the other children of its parent). Some code that took a <code>Node&lt;Integer&gt;</code> could call this and end up with a bunch of instances of <code>Node&lt;String&gt;</code> and start throwing <code>ClassCastExceptions</code>.</p> <p>You might consider making <code>SOIL</code> a <code>Set&lt;Node&lt;?&gt;&gt;</code> and not making it be the parent of all the roots. You could make it a static field somewhere, but make it private.</p>
 

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