{"id":410,"date":"2007-10-21T00:00:00","date_gmt":"2007-10-21T00:00:00","guid":{"rendered":"http:\/\/www.strongd.net\/?p=410"},"modified":"2007-10-21T00:00:00","modified_gmt":"2007-10-21T00:00:00","slug":"Generics Introduction","status":"publish","type":"post","link":"https:\/\/www.strongd.net\/?p=410","title":{"rendered":"Generics Introduction"},"content":{"rendered":"<p><DIV id=PageTitle>Introduction<\/DIV><br \/>\n<BLOCKQUOTE>In any nontrivial software project, bugs are simply a fact of life. Careful planning, programming, and testing can help reduce their pervasiveness, but somehow, somewhere, they&#8217;ll always find a way to creep into your code. This becomes especially apparent as new features are introduced and your code base grows in size and complexity.<br \/>\n<P>Fortunately, some bugs are easier to detect than others. Compile-time bugs, for example, tell you immediately that something is wrong; you can use the compiler&#8217;s error messages to figure out what the problem is and fix it, right then and there. Runtime bugs, however, can be much more problematic; they don&#8217;t always surface immediately, and when they do, it may be at a point in time that&#8217;s far removed from the actual cause of the problem. <\/P><br \/>\n<P>Generics add stability to your code by making more of your bugs detectable at compile time. Some programmers choose to learn generics by studying the Java Collections Framework; after all, generics <I>are<\/I> heavily used by those classes. However, since we haven&#8217;t yet covered collections, this chapter will focus primarily on simple &#8220;collections-like&#8221; examples that we&#8217;ll design from scratch. This hands-on approach will teach you the necessary syntax and terminology while demonstrating the various kinds of problems that generics were designed to solve. <\/P><br \/>\n<H3>A Simple Box Class<\/H3>Let&#8217;s begin by designing a nongeneric <CODE>Box<\/CODE> class that operates on objects of any type. It need only provide two methods: <CODE>add<\/CODE>, which adds an object to the box, and <CODE>get<\/CODE>, which retrieves it: <PRE>    public class Box {<\/p>\n<p>        private Object object;<\/p>\n<p>        public void add(Object object) {<br \/>\n            this.object = object;<br \/>\n        }<\/p>\n<p>        public Object get() {<br \/>\n            return object;<br \/>\n        }<br \/>\n    }<br \/>\n<\/PRE>Since its methods accept or return <CODE>Object<\/CODE>, you&#8217;re free to pass in whatever you want, provided that it&#8217;s not one of the primitive types. However, should you need to restrict the contained type to something specific (like <CODE>Integer<\/CODE>), your only option would be to specify the requirement in documentation (or in this case, a comment), which of course the compiler knows nothing about:<br \/>\n<BLOCKQUOTE><PRE>public class BoxDemo1 {<\/p>\n<p>    public static void main(String[] args) {<\/p>\n<p>        \/\/ ONLY place Integer objects into this box!<br \/>\n        Box integerBox = new Box();<\/p>\n<p>        integerBox.add(new Integer(10));<br \/>\n        Integer someInteger = (Integer)integerBox.get();<br \/>\n        System.out.println(someInteger);<br \/>\n    }<br \/>\n}<br \/>\n<\/PRE><\/BLOCKQUOTE>The <A class=SourceLink href=\"http:\/\/java.sun.com\/docs\/books\/tutorial\/java\/generics\/examples\/BoxDemo1.java\" target=_blank><CODE>BoxDemo1<\/CODE><\/A> program creates an <CODE>Integer<\/CODE> object, passes it to <CODE>add<\/CODE>, then assigns that same object to <CODE>someInteger<\/CODE> by the return value of <CODE>get<\/CODE>. It then prints the object&#8217;s value (10) to standard output. We know that the cast from <CODE>Object<\/CODE> to <CODE>Integer<\/CODE> is correct because we&#8217;ve honored the &#8220;contract&#8221; specified in the comment. But remember, the compiler knows nothing about this \u2014 it just trusts that our cast is correct. Furthermore, it will do nothing to prevent a careless programmer from passing in an object of the wrong type, such as <CODE>String<\/CODE>:<br \/>\n<BLOCKQUOTE><PRE>public class BoxDemo2 {<\/p>\n<p>    public static void main(String[] args) {<\/p>\n<p>        \/\/ ONLY place Integer objects into this box!<br \/>\n        Box integerBox = new Box();<\/p>\n<p>        \/\/ Imagine this is one part of a large application<br \/>\n        \/\/ modified by one programmer.<br \/>\n        integerBox.add(&#8220;10&#8221;); \/\/ note how the type is now String<\/p>\n<p>        \/\/ &#8230; and this is another, perhaps written<br \/>\n        \/\/ by a different programmer<br \/>\n        Integer someInteger = (Integer)integerBox.get();<br \/>\n        System.out.println(someInteger);<br \/>\n    }<br \/>\n}<br \/>\n<\/PRE><\/BLOCKQUOTE>In <A class=SourceLink href=\"http:\/\/java.sun.com\/docs\/books\/tutorial\/java\/generics\/examples\/BoxDemo2.java\" target=_blank><CODE>BoxDemo2<\/CODE><\/A> we&#8217;ve stored the number 10 as a <CODE>String<\/CODE>, which could be the case when, say, a GUI collects input from the user. However, the existing cast from <CODE>Object<\/CODE> to <CODE>Integer<\/CODE> has mistakenly been overlooked. This is clearly a bug, but because the code still compiles, you wouldn&#8217;t know anything is wrong until runtime, when the application crashes with a <CODE>ClassCastException<\/CODE>: <PRE>    Exception in thread &#8220;main&#8221;<br \/>\n         java.lang.ClassCastException:<br \/>\n            java.lang.String cannot be cast to java.lang.Integer<br \/>\n            at BoxDemo2.main(BoxDemo2.java:6)<br \/>\n<\/PRE><br \/>\n<P>If the <CODE>Box<\/CODE> class had been designed with generics in mind, this mistake would have been caught by the compiler, instead of crashing the application at runtime. <\/P><\/BLOCKQUOTE><br \/>\n<DIV><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In any nontrivial software project, bugs are simply a fact of life. Careful planning, programming, and testing can help reduce their pervasiveness, but somehow, somewhere, they&#8217;ll always find a way to creep into your code. This becomes especially apparent as new features are introduced and your code base grows in size and complexity. Fortunately, &hellip; <a href=\"https:\/\/www.strongd.net\/?p=410\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Generics Introduction<\/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-410","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/410","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=410"}],"version-history":[{"count":0,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/410\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=410"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=410"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=410"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}