× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Is there any reason to use generics in Java?

Francis Galiegue
Mar 01, 2015
<p>Well, if you don't use generics, you get to cast each time. You would have to:</p> <pre><code>// if raw List MyClass c = (MyClass) myClassList.get(0); // if List&lt;MyClass&gt; MyClass c = myClassList.get(0); </code></pre> <p>for instance.</p> <p>Yes, generics are erased at runtime, yes, they are here to enforce type safety at compile time only; however there is still runtime type erasure when you use bounds. Example:</p> <pre><code>public &lt;E extends RuntimeException&gt; E get(final Class&lt;E&gt; c, final Throwable t) { try { return (E) getHandle(c).invokeExact(t); } catch (Error | RuntimeException e) { throw e; } catch (Throwable oops) { final RuntimeException exception = new IllegalStateException(oops); exception.addSuppressed(t); throw exception; } } </code></pre> <p>The <code>E</code> here has a runtime type erasure; it <code>extends RuntimeException</code>. Therefore the cast is to <code>RuntimeException</code>, not <code>Object</code>.</p> <p>See the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#max-java.util.Collection-">javadoc of <code>Collections.max()</code></a> for another interesting example of runtime type erasure (hint: why does it define <code>T extends Object &amp; Comparable&lt;? super T&gt;</code> instead of <code>T extends Comparable&lt;? super T&gt;</code>?)</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/27689669/Is%20there%20any%20reason%20to%20use%20generics%20in%20Java?/27689743">Stack Overflow</a>.</p>
comments powered by Disqus