Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are looking for a library, my first thought was to use <a href="http://guava-libraries.googlecode.com/" rel="nofollow">Google Guava Libraries</a> as follows:</p> <pre><code>public &lt;T, U extends T&gt; List&lt;U&gt; homogenize(List&lt;T&gt; list, final Class&lt;U&gt; subclass) { Predicate&lt;T&gt; pred = new Predicate&lt;T&gt;() { @Override public boolean apply(T input) { return input.getClass().isAssignableFrom(subclass); } }; return Iterables.all(list, pred) ? (List&lt;U&gt;)list : null; } </code></pre> <p>I didn't try it out yet to make sure the kinks are out. However, I looked at it, and decided it was pretty butt-ugly. SLightly better Guava approach is:</p> <pre><code>public &lt;T, U extends T&gt; List&lt;U&gt; homogenize(List&lt;T&gt; list, Class&lt;U&gt; subclass) { Iterable&lt;U&gt; ret = Iterables.filter(list, subclass); if (list.size() != Lists.newArrayList(ret).size()) return null; return (List&lt;U&gt;)list; } </code></pre> <p>However, it's still a bit ugly. And it uses an internal copy of the collection. It does still return a cast view of the original. After all is said and done, the cleanest approach seems to use regular Java:</p> <pre><code>public &lt;T, U extends T&gt; List&lt;U&gt; homogenize(List&lt;T&gt; list, Class&lt;U&gt; subclass) { for( T t : list) { if (!t.getClass().isAssignableFrom(subclass)) return null; } return (List&lt;U&gt;)list; } </code></pre> <p>Depending on your aversion to typecast warnings, you could even drop the cast operators in all three options.</p> <p><strong>EDITS PER COMMENTS</strong> The following changes/improvements were suggested in the comments.</p> <p>Option one improved:</p> <pre><code>public &lt;T, U extends T&gt; List&lt;U&gt; homogenize(List&lt;T&gt; list, final Class&lt;U&gt; subclass) { return Iterables.all(list, Predicates.instanceOf(subclass)) ? (List&lt;U&gt;)list : null; } </code></pre> <p>Option two improved:</p> <pre><code>public &lt;T, U extends T&gt; List&lt;U&gt; homogenize(List&lt;T&gt; list, Class&lt;U&gt; subclass) { Iterable&lt;U&gt; ret = Iterables.filter(list, subclass); return (list.size() != Iterables.size(ret)) ? null : (List&lt;U&gt;)list; } </code></pre> <p>Option three improved:</p> <pre><code>public &lt;T, U extends T&gt; List&lt;U&gt; homogenize(List&lt;T&gt; list, Class&lt;U&gt; subclass) { for( T t : list) { if (!subclass.isInstance(t.getClass())) return null; } return (List&lt;U&gt;)list; } </code></pre> <p>With these improvements the 1st Guava example shines quite a bit. If you don't mind static imports, both Guava examples become extremely readable.</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