{"id":32,"date":"2020-12-11T15:27:17","date_gmt":"2020-12-11T15:27:17","guid":{"rendered":"https:\/\/www.canosielabs.com\/blog\/?p=32"},"modified":"2020-12-11T15:30:19","modified_gmt":"2020-12-11T15:30:19","slug":"guide-to-java-generics-the-problem","status":"publish","type":"post","link":"https:\/\/www.canosielabs.com\/blog\/guide-to-java-generics-the-problem\/","title":{"rendered":"Guide To Java Generics:  The problem"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">What are Generics and what are they used for?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Generics allow types (classes and interfaces) to be a parameter for classes, interfaces, and methods.  But what does that mean?  To start, we need to understand the problem generics are trying to solve.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Type Safety<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">What does it mean to be a <strong>statically typed<\/strong> language?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A language is <strong>statically typed<\/strong> if the type of a variable is known at compile time.  Java is statically typed since we know either i) declare the type of a variable in code or ii) the compiler can infer the type based on context.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What does<strong> type safety<\/strong> mean?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s important to know that statically typed and type safety are often wrongly interchanged but are actually two are separate concepts.  The definition of type safety is built of two parts.  First, a <strong>type error<\/strong> is error caused when there is a discrepancy between types in a operation or assignment.  Attempting to treat an Integer as a String is an example.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Safety<\/strong> means there are procedures and checks to ensure something does not happen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thus, languages that are <strong>type safe<\/strong>, have mechanisms to prevent operations type errors from occurring.  When the<strong> type safe<\/strong> checks are invoked are not part of the definition and is language dependent.  Languages like Java employ <strong>type checking<\/strong> at compile time, while others will employ it at runtime.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Java is statically typed and employs strict type checking at compile time.  This means that during compilation, the compiler validates that assignments and other operations on data are allowed by the data&#8217;s type. For example, if a variable is declared to be a type String, the compiler will prevent objects that are not Strings to be assigned to it.  The following code will cause a compile error (and flagged in your favorite IDE):<\/p>\n\n\n\n<pre><code class=\"language-java\">public void processTransaction(Integer rate) {\n    String str = rate; \/\/ error\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above code, we&#8217;re trying to assign data declared as an Integer to a variable declared as a String.  This isn&#8217;t allowed because the compiler knows the data is of type Integer and we&#8217;re trying to treat it as a String.<\/p>\n\n\n\n<br>&nbsp;\n\n\n\n<h2 class=\"wp-block-heading\">Heterogeneous Classes and Casting<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There are classes that operate on any type of object without caring what type of object it is.  Classes of the Java Collections Framework are examples. An instance of the same List class can be used to store Integers or Strings or any other object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But how do we accomplish this with type safety checks mentioned above?  Well, prior to generics,  most classes of the collection framework had signatures that used the type Object&#8230;and this is where we run into our first problems.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"602\" height=\"82\" src=\"https:\/\/www.canosielabs.com\/blog\/wp-content\/uploads\/2020\/12\/14javacollecctiondoc.png\" alt=\"\" class=\"wp-image-49\" srcset=\"https:\/\/www.canosielabs.com\/blog\/wp-content\/uploads\/2020\/12\/14javacollecctiondoc.png 602w, https:\/\/www.canosielabs.com\/blog\/wp-content\/uploads\/2020\/12\/14javacollecctiondoc-300x41.png 300w, https:\/\/www.canosielabs.com\/blog\/wp-content\/uploads\/2020\/12\/14javacollecctiondoc-250x34.png 250w, https:\/\/www.canosielabs.com\/blog\/wp-content\/uploads\/2020\/12\/14javacollecctiondoc-550x75.png 550w\" sizes=\"auto, (max-width: 602px) 100vw, 602px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Since all classes in Java extend Object, having the collection classes work with Object resolved our compile time errors but lead to two problems.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Casting<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, by declaring operations on List using type Object, the compiler doesn&#8217;t know what specific kind of object is stored in the List &#8211; even if <strong>we <\/strong>know what kind of objects are stored in there.  <\/p>\n\n\n\n<pre><code class=\"language-java\">List onlyStrings = new ArrayList();\nonlyStrings.add(\"abc\");\n\nObject whatTypeIsThis = onlyStrings.get(0);\n\n\/\/ type error since the compiler doesn't\n\/\/ that a String is there, even though, we know it.\nString value = onlyStrings.get(0);  \n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above code example, we have put a single String into the List.  Even if we absolutely know it&#8217;s a String, the compiler doesn&#8217;t know since the method signature of List#get() declares the return type as Object. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To get around this problem, developers resorted to casting objects into the types they wanted.<\/p>\n\n\n\n<pre><code class=\"language-java\">List onlyStrings = new ArrayList();\nonlyStrings.add(\"abc\");\n\nString value = (String)onlyStrings.get(0);  \n<\/code><\/pre>\n\n\n\n<br>&nbsp;\n\n\n\n<h3 class=\"wp-block-heading\">Losing Type Safety<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Second, by declaring everything as type Object, we are circumventing any compile time type safety checks.  This means our list, which should only hold Strings, could now potentially hold mixed types &#8211; causing runtime errors.<\/p>\n\n\n\n<pre><code class=\"language-java\">List onlyStrings = new ArrayList();\nonlyStrings.add(\"abc\");\nonlyStrings.add(new Integer(1)); \/\/ oops\n\n\/\/ runtime error since the object at \n\/\/ index 1 is of type Integer\nString value = (String)onlyStrings.get(1); \n<\/code><\/pre>\n\n\n\n<br>&nbsp;\n\n\n\n<h2 class=\"wp-block-heading\">The problem Statement<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In many cases, the casting required to avoid type errors provided no real benefit and just cluttered up.  In addition, the use of type Object to by-pass compilation errors introduced the loss of type safety, one of the major benefits of Java.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a developer knows what kind of types should be in a array, they should be able to provide it as a &#8216;parameter&#8217; during instance creation.  Since this instance is bound to hold only objects of those types, the compiler should be able to detect if a developer is attempting to add some other type and flag it as a type error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Generics, enter stage left<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Generics introduces a mechanism for developers to create <strong>parametrized types<\/strong>.  In other words, it allows developers to make types into parameters that are passed in as <em>&#8220;arguments&#8221;<\/em> when a generic class is instantiated or generic method is invoked.  Let&#8217;s take a look at a brief example:<\/p>\n\n\n\n<pre><code class=\"language-java\">List&lt;String&gt; onlyStrings = new ArrayList&lt;&gt;();\nonlyStrings.add(\"abc\");\nonlyStrings.add(new Integer(1)); \/\/ compile time error\n\n\/\/ no more casting required, since the \n\/\/ compiler 'knows' the List only stores Strings.\nString value = onlyStrings.get(1); \n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The List is now being declared to only hold Strings (via the &lt;String&gt; syntax) and since the compiler now knows only Strings should be be inserted, it can flag type errors when we attempt to insert a Integer.  In addition, we no longer need the &#8216;meaningless casting&#8217; used when retrieving a value from the List.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the next chapter, we take brief look at generic syntax and usage.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What are Generics and what are they used for? Generics allow types (classes and interfaces) to be a parameter for classes, interfaces, and methods. But&hellip;<\/p>\n","protected":false},"author":3,"featured_media":236,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"bgseo_title":"","bgseo_description":"","bgseo_robots_index":"index","bgseo_robots_follow":"follow","footnotes":""},"categories":[1],"tags":[4,3,5,6],"class_list":["post-32","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized","tag-generics","tag-java","tag-prgramming","tag-software-development"],"_links":{"self":[{"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/posts\/32","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/comments?post=32"}],"version-history":[{"count":10,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/posts\/32\/revisions"}],"predecessor-version":[{"id":233,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/posts\/32\/revisions\/233"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/media\/236"}],"wp:attachment":[{"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/media?parent=32"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/categories?post=32"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.canosielabs.com\/blog\/wp-json\/wp\/v2\/tags?post=32"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}