Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So if I understand you correctly, you want to be able to construct a list of ClassA or a list of ClassB depending on if a given object is ClassA or ClassB.</p> <pre><code>public List&lt;? extends Object&gt; getList(Object e) { List&lt;? extends Object&gt; list = new ArrayList&lt;? extends Object&gt;(); if(e instanceof ClassA) { List&lt;ClassA&gt; listA = new ArrayList&lt;ClassA&gt;(); // Populate list somehow list = listA; } else if (e instanceof ClassB) { List&lt;ClassB&gt; listB = new ArrayList&lt;ClassB&gt;(); // Populate list somehow list = listB; } return list; } </code></pre> <p>Unfortunately, the return type must allow for either type (you can alternatively create two methods with different return types, but they must have different names). However, this allows you to use listA and listB as their own types before assigning it to the more generic list.</p> <p>However this is a violation of the <a href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29" rel="nofollow">SOLID principal</a>, so an alternative might be:</p> <pre><code>public abstract class Root&lt;T&gt; { public abstract List&lt;T&gt; getList(); } public class ClassAList extends Root&lt;ClassA&gt; { @Override public List&lt;ClassA&gt; getList() { List&lt;ClassA&gt; list = new ArrayList&lt;ClassA&gt;(); // Populate list somehow return list; } } public class ClassBList extends Root&lt;ClassB&gt; { @Override public List&lt;ClassB&gt; getList() { List&lt;ClassB&gt; list = new ArrayList&lt;ClassB&gt;(); // Populate list somehow return list; } } </code></pre> <p>Hope that helps!</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