Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unfortunately I don't think this kind of "if Comparable do this else do that" logic is possible with the Java type system.</p> <p>You could split the Comparable and non-Comparable cases into separate classes and hide them behind an interface, something like this:</p> <pre><code>interface Interface&lt;T&gt; { public void processData(); } class MyClass&lt;T&gt; implements Interface&lt;T&gt; { private final Collection&lt;? extends T&gt; data; MyClass(Comparator&lt;T&gt; comparator, Collection&lt;? extends T&gt; data) { this.data = data; } public void processData() { // ... } } class MyCompClass&lt;T extends Comparable&lt;T&gt;&gt; implements Interface&lt;T&gt; { private final Collection&lt;? extends T&gt; data; MyCompClass(Collection&lt;? extends T&gt; data) { this.data = data; } public void processData() { // ... } } class Factory { static &lt;T extends Comparable&lt;T&gt;&gt; Interface&lt;T&gt; create(Collection&lt;? extends T&gt; data) { return new MyCompClass&lt;T&gt;(data); } static &lt;T&gt; Interface&lt;T&gt; create(Comparator&lt;T&gt; comparator, Collection&lt;? extends T&gt; data) { return new MyClass&lt;T&gt;(comparator, data); } } </code></pre> <p>But this might result in a lot of duplicated code. Another option is to leave MyClass requiring a Comparator in its constructor, and build that comparator in the factory:</p> <pre><code>class MyClass&lt;T&gt; { private final Collection&lt;? extends T&gt; data; MyClass(Comparator&lt;T&gt; comparator, Collection&lt;? extends T&gt; data) { this.data = data; } public void processData() { // ... } } class Factory { static &lt;T extends Comparable&lt;T&gt;&gt; MyClass&lt;T&gt; create(Collection&lt;? extends T&gt; data) { return new MyClass&lt;T&gt;(new Comparator&lt;T&gt;() { public int compare(T o1, T o2) { return o1.compareTo(o2); } }, data); } static &lt;T&gt; MyClass&lt;T&gt; create(Comparator&lt;T&gt; comparator, Collection&lt;? extends T&gt; data) { return new MyClass&lt;T&gt;(comparator, data); } } </code></pre>
 

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