{"id":411,"date":"2007-10-21T00:00:00","date_gmt":"2007-10-21T00:00:00","guid":{"rendered":"http:\/\/www.strongd.net\/?p=411"},"modified":"2007-10-21T00:00:00","modified_gmt":"2007-10-21T00:00:00","slug":"Generic Types","status":"publish","type":"post","link":"https:\/\/www.strongd.net\/?p=411","title":{"rendered":"Generic Types"},"content":{"rendered":"<p><DIV id=PageTitle>Generic Types<\/DIV><br \/>\n<BLOCKQUOTE><br \/>\n<P>Let&#8217;s update our <CODE>Box<\/CODE> class to use generics. We&#8217;ll first create a <I>generic type declaration<\/I> by changing the code &#8220;<CODE>public class Box<\/CODE>&#8221; to &#8220;<CODE>public class Box&lt;T&gt;<\/CODE>&#8220;; this introduces one <I>type variable<\/I>, named <CODE>T<\/CODE>, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There&#8217;s nothing particularly complex about this concept. In fact, it&#8217;s quite similar to what you already know about variables in general. Just think of <CODE>T<\/CODE> as a special kind of variable, whose &#8220;value&#8221; will be whatever type you pass in; this can be any class type, any interface type, or even another type variable. It just can&#8217;t be any of the primitive data types. In this context, we also say that <CODE>T<\/CODE> is a <I>formal type parameter<\/I> of the <CODE>Box<\/CODE> class. <\/P><PRE>\/**<br \/>\n * Generic version of the Box class.<br \/>\n *\/<br \/>\npublic class Box<B>&lt;T&gt;<\/B> {<\/p>\n<p>    private <B>T t<\/B>; \/\/ T stands for &#8220;Type&#8221;          <\/p>\n<p>    public void add(<B>T t<\/B>) {<br \/>\n        this.<B>t<\/B> = <B>t<\/B>;<br \/>\n    }<\/p>\n<p>    public <B>T<\/B> get() {<br \/>\n        return <B>t<\/B>;<br \/>\n    }<br \/>\n}<br \/>\n<\/PRE><br \/>\n<P>As you can see, we&#8217;ve replaced all occurrences of <CODE>Object<\/CODE> with <CODE>T<\/CODE>. To reference this generic class from within your own code, you must perform a <I>generic type invocation<\/I>, which replaces <CODE>T<\/CODE> with some concrete value, such as <CODE>Integer<\/CODE>: <\/P><br \/>\n<BLOCKQUOTE><PRE>Box&lt;Integer&gt; integerBox;<br \/>\n<\/PRE><\/BLOCKQUOTE>You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you&#8217;re passing a <I>type argument<\/I> \u2014 <CODE>Integer<\/CODE> in this case \u2014 to the <CODE>Box<\/CODE> class itself. Like any other variable declaration, this code does not actually create a new <CODE>Box<\/CODE> object. It simply declares that <CODE>integerBox<\/CODE> will hold a reference to a &#8220;<CODE>Box<\/CODE> of <CODE>Integer<\/CODE>&#8220;, which is how <CODE>Box&lt;Integer&gt;<\/CODE> is read.<br \/>\n<P>An invocation of a generic type is generally known as a <I>parameterized type<\/I>. <\/P><br \/>\n<P><\/P><br \/>\n<P>To instantiate this class, use the <CODE>new<\/CODE> keyword, as usual, but place <CODE>&lt;Integer&gt;<\/CODE> between the class name and the parenthesis: <\/P><br \/>\n<BLOCKQUOTE><PRE>integerBox = new Box&lt;Integer&gt;();<br \/>\n<\/PRE><\/BLOCKQUOTE><br \/>\n<P>Or, you can put the entire statement on one line, such as: <\/P><br \/>\n<BLOCKQUOTE><PRE>Box&lt;Integer&gt; integerBox = new Box&lt;Integer&gt;();<br \/>\n<\/PRE><\/BLOCKQUOTE><br \/>\n<P>Once <CODE>integerBox<\/CODE> is initialized, you&#8217;re free to invoke its <CODE>get<\/CODE> method without providing a cast, as in <A class=SourceLink href=\"http:\/\/java.sun.com\/docs\/books\/tutorial\/java\/generics\/examples\/BoxDemo3.java\" target=_blank><CODE>BoxDemo3<\/CODE><\/A>: <\/P><br \/>\n<BLOCKQUOTE><PRE>public class BoxDemo3 {<\/p>\n<p>    public static void main(String[] args) {<br \/>\n        Box&lt;Integer&gt; integerBox = new Box&lt;Integer&gt;();<br \/>\n        integerBox.add(new Integer(10));<br \/>\n        Integer someInteger = integerBox.get(); \/\/ no cast!<br \/>\n        System.out.println(someInteger);<br \/>\n    }<br \/>\n}<br \/>\n<\/PRE><\/BLOCKQUOTE>Furthermore, if you try adding an incompatible type to the box, such as <CODE>String<\/CODE>, compilation will fail, alerting you to what previously would have been a runtime bug: <PRE>    BoxDemo3.java:5: add(java.lang.Integer) in Box&lt;java.lang.Integer&gt;<br \/>\n    cannot be applied to (java.lang.String)<br \/>\n        integerBox.add(&#8220;10&#8221;);<br \/>\n                  ^<br \/>\n    1 error<br \/>\n<\/PRE><br \/>\n<P>It&#8217;s important to understand that type variables are not actually types themselves. In the above examples, you won&#8217;t find <CODE>T.java<\/CODE> or <CODE>T.class<\/CODE> anywhere on the filesystem. Furthermore, <CODE>T<\/CODE> is not a part of the <CODE>Box<\/CODE> class name. In fact during compilation, all generic information will be removed entirely, leaving only <CODE>Box.class<\/CODE> on the filesystem. We&#8217;ll discuss this later in the section on <A class=TutorialLink href=\"http:\/\/java.sun.com\/docs\/books\/tutorial\/java\/generics\/erasure.html\" target=_top>Type Erasure<\/A> <\/P><br \/>\n<P>Also note that a generic type may have multiple type parameters, but each parameter must be unique within its declaring class or interface. A declaration of <CODE>Box&lt;T,T&gt;<\/CODE>, for example, would generate an error on the second occurrence of <CODE>T<\/CODE>, but <CODE>Box&lt;T,U&gt;<\/CODE>, however, would be allowed. <\/P><br \/>\n<P><\/P><br \/>\n<H3>Type Parameter Naming Conventions<\/H3>By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable <A class=TutorialLink href=\"http:\/\/java.sun.com\/docs\/books\/tutorial\/java\/nutsandbolts\/variables.html#naming\" target=_top>naming<\/A> conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.<br \/>\n<P>The most commonly used type parameter names are: <\/P><br \/>\n<UL><br \/>\n<LI>E &#8211; Element (used extensively by the Java Collections Framework) <\/LI><br \/>\n<LI>K &#8211; Key <\/LI><br \/>\n<LI>N &#8211; Number <\/LI><br \/>\n<LI>T &#8211; Type <\/LI><br \/>\n<LI>V &#8211; Value <\/LI><br \/>\n<LI>S,U,V etc. &#8211; 2nd, 3rd, 4th types <\/LI><\/UL>You&#8217;ll see these names used throughout the Java SE API and the rest of this tutorial. <\/BLOCKQUOTE><br \/>\n<DIV><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Generic Types Let&#8217;s update our Box class to use generics. We&#8217;ll first create a generic type declaration by changing the code &#8220;public class Box&#8221; to &#8220;public class Box&lt;T&gt;&#8220;; this introduces one type variable, named T, that can be used anywhere inside the class. This same technique can be applied to interfaces as well. There&#8217;s nothing &hellip; <a href=\"https:\/\/www.strongd.net\/?p=411\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Generic Types<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-411","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/411","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=411"}],"version-history":[{"count":0,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/411\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}