{"id":1022,"date":"2023-08-24T01:37:23","date_gmt":"2023-08-24T01:37:23","guid":{"rendered":"https:\/\/www.w3computing.com\/articles\/?p=1022"},"modified":"2023-08-24T01:37:27","modified_gmt":"2023-08-24T01:37:27","slug":"java-generics-basic-advanced","status":"publish","type":"post","link":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/","title":{"rendered":"Mastering Java Generics: From Basic to Advanced"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Java has undergone numerous evolutions since its inception in the mid-&#8217;90s. Its adaptability and commitment to improvement have been some of the pivotal reasons for its widespread adoption. One such significant improvement was the introduction of Generics in Java 5.0.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Brief History and Need for Java Generics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Before the arrival of Generics, Java developers often used the collections (like <code>ArrayList<\/code> or <code>HashMap<\/code>) to store and manage objects. However, these collections had a drawback: they could hold any type of object. This lack of type-safety meant that runtime type-casting was common, leading to potential runtime errors due to incorrect casting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine pouring a mix of liquids\u2014water, juice, milk\u2014into the same container. When you need a glass of milk, you&#8217;d have to carefully pick through the mix to ensure you only get milk, and even then, there\u2019s a risk of contamination. This was the world of Java without Generics.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Enter Generics in Java 5.0. The addition allowed developers to provide a type parameter to collections, ensuring type safety. Using our previous analogy, it was like having labeled containers for each liquid. If you wanted a glass of milk, you\u2019d go to the milk container. This ensured not only ease but also safety, as the risk of contamination reduced drastically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Generics brought about a type-safe environment, reducing the need for runtime type checking and casts, leading to more robust and maintainable code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Overview of the Tutorial<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">As we progress in this tutorial, we will go deep into Java Generics. From understanding the basic concepts of Generic Classes, Methods, and Interfaces, we will explore advanced topics like Bounded Type Parameters, Wildcards, and Type Erasure. Each section will be accompanied by practical code examples, ensuring that you not only grasp the theoretical knowledge but also the practical application of Generics in real-world scenarios.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Use Generics?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The introduction of Generics in Java was not just a sophisticated language feature meant to impress developers. It was introduced as a solution to real-world challenges Java developers faced in their coding journey. Let&#8217;s break down the core reasons for using Generics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Code Safety with Type Checks<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Without Generics, Java collections stored objects of the type <code>Object<\/code>. This meant that a developer could inadvertently insert an unwanted type into a collection, leading to potential issues later on.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With Generics, we can specify the exact type of elements a collection can hold. This is done at compile-time, ensuring that any violations of this rule are flagged immediately. For instance:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;String&gt; names = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\nnames.add(<span class=\"hljs-string\">\"John\"<\/span>);   <span class=\"hljs-comment\">\/\/ Allowed<\/span>\r\nnames.add(<span class=\"hljs-number\">123<\/span>);      <span class=\"hljs-comment\">\/\/ Compile-time error<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above code, trying to add an integer to a list declared to hold strings results in a compile-time error. This immediate feedback means developers can address issues before the code even runs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Reduction of Runtime Errors and Casts<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prior to Generics, retrieving data from collections often required casting. If you made an error in casting, it would result in a runtime exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List names = <span class=\"hljs-keyword\">new<\/span> ArrayList();\r\nnames.add(<span class=\"hljs-string\">\"John\"<\/span>);\r\nString name = (String) names.get(<span class=\"hljs-number\">0<\/span>);   <span class=\"hljs-comment\">\/\/ Requires casting<\/span>\r\nInteger num = (Integer) names.get(<span class=\"hljs-number\">0<\/span>);  <span class=\"hljs-comment\">\/\/ Runtime exception<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">With Generics, the need for casting is eliminated because the compiler knows the type of elements in the collection:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">List&lt;<span class=\"hljs-built_in\">String<\/span>&gt; names = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\nnames.add(<span class=\"hljs-string\">\"John\"<\/span>);\r\n<span class=\"hljs-built_in\">String<\/span> name = names.get(<span class=\"hljs-number\">0<\/span>);  <span class=\"hljs-comment\">\/\/ No casting required<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This not only reduces the risk of <code>ClassCastException<\/code> at runtime but also makes the code cleaner.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">More Readable and Maintainable Code<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Code clarity is essential for maintainability. With Generics, by merely looking at the code, a developer can instantly understand the type of data structures and their elements, leading to quicker comprehension of the code&#8217;s function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Consider two method signatures:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">processData<\/span><span class=\"hljs-params\">(List data)<\/span> <\/span>{...}\r\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">processData<\/span><span class=\"hljs-params\">(List&lt;Student&gt; data)<\/span> <\/span>{...}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The latter, with Generics, immediately conveys that the method is designed to process a list of <code>Student<\/code> objects, making the code more self-explanatory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Moreover, as projects grow, ensuring that data structures are used consistently becomes paramount. Generics assists in enforcing this consistency, making the codebase more maintainable in the long run.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Concepts of Generics<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Generic Classes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Generic classes allow you to define a class with one or more type parameters. These type parameters act as placeholders that are later replaced with actual types when an object of the generic class is created. Let&#8217;s dive into understanding them better.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Creating a Simple Generic Class<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Consider a scenario where you want a class to hold a pair of objects, but you don\u2019t want to restrict the types of objects that can be paired. Here&#8217;s how you can achieve this using a generic class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Pair<\/span>&lt;<span class=\"hljs-title\">T1<\/span>, <span class=\"hljs-title\">T2<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-keyword\">private<\/span> T1 first;\r\n    <span class=\"hljs-keyword\">private<\/span> T2 second;\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Pair<\/span><span class=\"hljs-params\">(T1 first, T2 second)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.first = first;\r\n        <span class=\"hljs-keyword\">this<\/span>.second = second;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> T1 <span class=\"hljs-title\">getFirst<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> first;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> T2 <span class=\"hljs-title\">getSecond<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> second;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">setFirst<\/span><span class=\"hljs-params\">(T1 first)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.first = first;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">setSecond<\/span><span class=\"hljs-params\">(T2 second)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.second = second;\r\n    }\r\n}\r\n\r\n<span class=\"hljs-comment\">\/\/ Usage:<\/span>\r\nPair&lt;String, Integer&gt; nameAndAge = <span class=\"hljs-keyword\">new<\/span> Pair&lt;&gt;(<span class=\"hljs-string\">\"John\"<\/span>, <span class=\"hljs-number\">25<\/span>);\r\nString name = nameAndAge.getFirst();\r\nInteger age = nameAndAge.getSecond();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above code, <code>Pair<\/code> is a generic class with two type parameters: <code>T1<\/code> and <code>T2<\/code>. When creating an instance of <code>Pair<\/code>, you specify the types for <code>T1<\/code> and <code>T2<\/code>, which in this case are <code>String<\/code> and <code>Integer<\/code>, respectively.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of Using Generic Classes<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Type Safety<\/strong>: The primary advantage of generic classes is type safety. As seen in the <code>Pair<\/code> example, once the types are set for the object, any attempt to use the wrong types will result in a compile-time error. This can save developers from runtime exceptions and potential bugs.<\/li>\n\n\n\n<li><strong>Reusability<\/strong>: One of the significant benefits of generic classes is code reusability. Rather than creating separate classes for each type, you can define a single generic class that works with different types.<\/li>\n\n\n\n<li><strong>Elimination of Casts<\/strong>: Without generics, you&#8217;d have to use casting when retrieving objects from classes that hold general object types. With generic classes, the need for casting is eliminated, making the code cleaner and safer.<\/li>\n\n\n\n<li><strong>Self-Documenting<\/strong>: When you look at a generic class&#8217;s usage in code, you instantly understand what types it operates upon. For example, <code>Pair&lt;String, Integer&gt;<\/code> immediately tells you that the <code>Pair<\/code> object holds a <code>String<\/code> and an <code>Integer<\/code>.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Generic Methods<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">While generic classes allow you to abstract a whole class with a type parameter, sometimes, you might only need to make a single method generic, irrespective of the class. This is where generic methods come in.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Writing a Generic Method<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s consider you want to write a utility method that swaps the positions of two elements in an array. Here&#8217;s how you can create such a method using generics:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Utility<\/span> <\/span>{\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">swap<\/span><span class=\"hljs-params\">(T&#91;] array, <span class=\"hljs-keyword\">int<\/span> pos1, <span class=\"hljs-keyword\">int<\/span> pos2)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">if<\/span> (pos1 &lt; <span class=\"hljs-number\">0<\/span> || pos1 &gt;= array.length || pos2 &lt; <span class=\"hljs-number\">0<\/span> || pos2 &gt;= array.length) {\r\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> IllegalArgumentException(<span class=\"hljs-string\">\"Position out of bounds!\"<\/span>);\r\n        }\r\n        \r\n        T temp = array&#91;pos1];\r\n        array&#91;pos1] = array&#91;pos2];\r\n        array&#91;pos2] = temp;\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the method signature, <code>&lt;T&gt;<\/code> indicates that <code>swap<\/code> is a generic method. It operates on an array of any type <code>T<\/code>. The method then swaps the elements at the specified positions. Note that this method can work for arrays of any object type, like <code>Integer<\/code>, <code>String<\/code>, or custom objects.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How to Call a Generic Method<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">While Java&#8217;s compiler is often smart enough to infer the type arguments when calling a generic method (this is known as type inference), you can also explicitly provide the type if required. Here&#8217;s how:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using Type Inference<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Given the earlier <code>swap<\/code> method, if you have an <code>Integer<\/code> array and you want to swap two elements, you simply call:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">Integer&#91;] numbers = {<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">5<\/span>};\r\nUtility.swap(numbers, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">3<\/span>); <span class=\"hljs-comment\">\/\/ swaps the numbers at positions 1 and 3<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The compiler will infer the type <code>T<\/code> to be <code>Integer<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Explicitly Providing the Type<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Although not necessary in many cases, you can provide the type explicitly using the diamond (<code>&lt;><\/code>) operator:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">String&#91;] words = {<span class=\"hljs-string\">\"apple\"<\/span>, <span class=\"hljs-string\">\"banana\"<\/span>, <span class=\"hljs-string\">\"cherry\"<\/span>};\r\nUtility.&lt;String&gt;swap(words, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">2<\/span>); <span class=\"hljs-comment\">\/\/ swaps \"apple\" and \"cherry\"<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here, we&#8217;re explicitly telling the compiler that we&#8217;re calling the <code>swap<\/code> method with type <code>String<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Generic Interfaces<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Just like classes and methods, interfaces in Java can also be generic. This means you can specify one or more type parameters when declaring an interface. This can be particularly useful when designing APIs that need flexibility across a range of types.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Implementing a Generic Interface<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a simple generic interface named <code>Comparator<\/code>, which determines the ordering between two objects of the same type:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-comment\">\/\/ Generic interface<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">interface<\/span> <span class=\"hljs-title\">Comparator<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-comment\">\/**\r\n     * Compares two objects and returns:\r\n     * - A negative integer if obj1 is less than obj2\r\n     * - Zero if obj1 is equal to obj2\r\n     * - A positive integer if obj1 is greater than obj2\r\n     *\/<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">compare<\/span><span class=\"hljs-params\">(T obj1, T obj2)<\/span><\/span>;\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s implement this interface for a <code>Person<\/code> class, where the comparison is based on their age:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">private<\/span> String name;\r\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">int<\/span> age;\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Person<\/span><span class=\"hljs-params\">(String name, <span class=\"hljs-keyword\">int<\/span> age)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.name = name;\r\n        <span class=\"hljs-keyword\">this<\/span>.age = age;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">getAge<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> age;\r\n    }\r\n    \r\n    <span class=\"hljs-comment\">\/\/ More methods for Person class...<\/span>\r\n}\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">PersonAgeComparator<\/span> <span class=\"hljs-keyword\">implements<\/span> <span class=\"hljs-title\">Comparator<\/span>&lt;<span class=\"hljs-title\">Person<\/span>&gt; <\/span>{\r\n\r\n    <span class=\"hljs-meta\">@Override<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">compare<\/span><span class=\"hljs-params\">(Person p1, Person p2)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> Integer.compare(p1.getAge(), p2.getAge());\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the example above, the <code>Comparator<\/code> interface is generic, allowing for the comparison of any two objects of the same type. By implementing this interface in <code>PersonAgeComparator<\/code>, we provide a specific comparison strategy for <code>Person<\/code> objects based on their age.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You could further implement more comparators for the <code>Person<\/code> class, perhaps based on name, height, or any other attribute, without altering the original <code>Comparator<\/code> interface definition.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Bounded Type Parameters<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Upper Bounded Wildcards (<code>extends<\/code> keyword)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java generics, wildcards enable more flexibility in using generic types, especially when dealing with inheritance and interfaces. The keyword <code>extends<\/code> is employed not only for classes but for interfaces as well, providing an upper bound to the wildcard.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Upper Bounded Wildcards specify a bound for the unknown type, allowing it to accept types that are a subtype of the specified bound.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Limiting Types with Upper Bounds<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose you have a series of number classes like <code>Integer<\/code>, <code>Double<\/code>, etc., and you want a method that computes the sum of a list of any of these numeric types:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T extends Number&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">double<\/span> <span class=\"hljs-title\">sumOfList<\/span><span class=\"hljs-params\">(List&lt;T&gt; list)<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">double<\/span> sum = <span class=\"hljs-number\">0.0<\/span>;\r\n    <span class=\"hljs-keyword\">for<\/span> (T num : list) {\r\n        sum += num.doubleValue();\r\n    }\r\n    <span class=\"hljs-keyword\">return<\/span> sum;\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The <code>Number<\/code> class is a part of Java&#8217;s standard library, and classes like <code>Integer<\/code>, <code>Double<\/code>, <code>Float<\/code>, etc., are all subclasses of <code>Number<\/code>. This method takes a list of any subtype of <code>Number<\/code> and calculates the sum.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;Integer&gt; intList = Arrays.asList(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">5<\/span>);\r\nSystem.out.println(sumOfList(intList));  <span class=\"hljs-comment\">\/\/ Outputs: 15.0<\/span>\r\n\r\nList&lt;Double&gt; doubleList = Arrays.asList(<span class=\"hljs-number\">1.1<\/span>, <span class=\"hljs-number\">2.2<\/span>, <span class=\"hljs-number\">3.3<\/span>);\r\nSystem.out.println(sumOfList(doubleList));  <span class=\"hljs-comment\">\/\/ Outputs: 6.6<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above method, the <code>&lt;T extends Number&gt;<\/code> syntax signifies that the method accepts lists of any type <code>T<\/code>, as long as <code>T<\/code> is a subtype of <code>Number<\/code> (i.e., either <code>Number<\/code> itself or a subclass of <code>Number<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By using an upper bounded wildcard, we&#8217;ve limited the kind of lists the <code>sumOfList<\/code> method can accept, ensuring type safety, while still allowing a certain degree of flexibility.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Lower Bounded Wildcards (<code>super<\/code> keyword)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">While the upper bounded wildcard restricts unknown types to a particular type or a subtype of that type, the lower bounded wildcard does the opposite. It restricts the unknown type to be a particular type or a <strong>super type<\/strong> of that type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lower Bounded Wildcards come into play when you want to ensure that an object is an instance of a certain class or its parent classes. The <code>super<\/code> keyword is used for setting the lower bound.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Using Lower Bounds<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Consider you have a method that inserts elements into a list, and you want this method to accept lists of a type or its super types. Here&#8217;s a scenario with a simple class hierarchy:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Animal<\/span> <\/span>{}\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Bird<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Animal<\/span> <\/span>{}\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Sparrow<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Bird<\/span> <\/span>{}\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">addBirds<\/span><span class=\"hljs-params\">(List&lt;? <span class=\"hljs-keyword\">super<\/span> Bird&gt; list)<\/span> <\/span>{\r\n    list.add(<span class=\"hljs-keyword\">new<\/span> Bird());\r\n    list.add(<span class=\"hljs-keyword\">new<\/span> Sparrow());\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The <code>addBirds<\/code> method is defined to accept a list of any type that is a super type of <code>Bird<\/code> (including <code>Bird<\/code> itself). This means you can pass in a <code>List&lt;Bird&gt;<\/code>, <code>List&lt;Animal&gt;<\/code>, but not a <code>List&lt;Sparrow&gt;<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;Animal&gt; animalList = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\naddBirds(animalList);\r\n<span class=\"hljs-comment\">\/\/ animalList now contains instances of Bird and Sparrow<\/span>\r\n\r\nList&lt;Bird&gt; birdList = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\naddBirds(birdList);\r\n<span class=\"hljs-comment\">\/\/ birdList also contains instances of Bird and Sparrow<\/span>\r\n\r\nList&lt;Sparrow&gt; sparrowList = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\n<span class=\"hljs-comment\">\/\/ addBirds(sparrowList);  \/\/ Compile-time error!<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above example, the lower bounded wildcard <code>? super Bird<\/code> ensures that the list passed to <code>addBirds<\/code> can safely hold instances of <code>Bird<\/code> and any subclass of <code>Bird<\/code> (like <code>Sparrow<\/code>). This enforces type safety in such a way that you can&#8217;t accidentally insert a <code>Bird<\/code> into a list that is designed to hold only specific subtypes of <code>Bird<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Multiple Bounds<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java, type parameters can be bounded by multiple constraints. This allows for a type parameter to be restricted to subtypes of multiple types. The syntax for multiple bounds involves using the <code>extends<\/code> keyword followed by the type bounds separated by <code>&amp;<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Multiple Bounds come into play when you want a generic type to adhere to multiple type constraints. This is especially useful when combining class and interface constraints.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Combining Bounds<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose you want a generic method to sort elements based on their natural ordering (<code>Comparable<\/code>) and at the same time, you want to ensure that they are serializable. Here&#8217;s how you can do this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Utils<\/span> <\/span>{\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T extends Comparable&lt;T&gt; &amp; Serializable&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">sortAndSave<\/span><span class=\"hljs-params\">(List&lt;T&gt; list, File file)<\/span> <\/span>{\r\n        Collections.sort(list);\r\n        \r\n        <span class=\"hljs-keyword\">try<\/span> (ObjectOutputStream out = <span class=\"hljs-keyword\">new<\/span> ObjectOutputStream(<span class=\"hljs-keyword\">new<\/span> FileOutputStream(file))) {\r\n            <span class=\"hljs-keyword\">for<\/span> (T item : list) {\r\n                out.writeObject(item);\r\n            }\r\n        } <span class=\"hljs-keyword\">catch<\/span> (IOException e) {\r\n            e.printStackTrace();\r\n        }\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, the method <code>sortAndSave<\/code> has a type parameter <code>T<\/code> that extends both <code>Comparable&lt;T&gt;<\/code> and <code>Serializable<\/code>. This ensures:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>You can sort the list since <code>T<\/code> is <code>Comparable<\/code>.<\/li>\n\n\n\n<li>You can serialize each item in the list to a file since <code>T<\/code> is <code>Serializable<\/code>.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;String&gt; names = Arrays.asList(<span class=\"hljs-string\">\"Alice\"<\/span>, <span class=\"hljs-string\">\"Bob\"<\/span>, <span class=\"hljs-string\">\"Charlie\"<\/span>);\r\nFile file = <span class=\"hljs-keyword\">new<\/span> File(<span class=\"hljs-string\">\"sortedNames.dat\"<\/span>);\r\nUtils.sortAndSave(names, file);  <span class=\"hljs-comment\">\/\/ This works since String implements Comparable and Serializable<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the case of multiple bounds, if one of the bounds is a class, it must be specified first. This is important to note since Java doesn&#8217;t support multiple class inheritance, but a class can implement multiple interfaces.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wildcards in Generics<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">The Unbounded Wildcard (<code>?<\/code> keyword)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java generics, the unbounded wildcard (<code>?<\/code>) is a type argument that stands for an unknown type. It&#8217;s especially useful when you need to work with generic objects but don&#8217;t know or don&#8217;t care about their actual type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Unbounded Wildcard is denoted by the <code><strong>?<\/strong><\/code> symbol and means that the type is unknown. It provides maximum flexibility but can also restrict certain operations since you don&#8217;t know the type of objects contained within the generic structure.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example: Working with Raw Types<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Consider you want to create a method that prints out the elements of any list, regardless of the list&#8217;s type:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">printList<\/span><span class=\"hljs-params\">(List&lt;?&gt; list)<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">for<\/span> (Object obj : list) {\r\n        System.out.println(obj);\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here, <code>List&lt;?&gt;<\/code> denotes a list of an unknown type. It can be a <code>List&lt;String&gt;<\/code>, <code>List&lt;Integer&gt;<\/code>, or a <code>List<\/code> of any other type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;String&gt; names = Arrays.asList(<span class=\"hljs-string\">\"Alice\"<\/span>, <span class=\"hljs-string\">\"Bob\"<\/span>, <span class=\"hljs-string\">\"Charlie\"<\/span>);\r\nprintList(names);  <span class=\"hljs-comment\">\/\/ Outputs: Alice, Bob, Charlie<\/span>\r\n\r\nList&lt;Integer&gt; numbers = Arrays.asList(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">5<\/span>);\r\nprintList(numbers);  <span class=\"hljs-comment\">\/\/ Outputs: 1, 2, 3, 4, 5<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">While the unbounded wildcard provides flexibility, there are limitations. For instance, you can&#8217;t add elements to the list within the <code>printList<\/code> method because the type is unknown. The only exception is <code>null<\/code>, which is a member of every type:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">addNull<\/span><span class=\"hljs-params\">(List&lt;?&gt; list)<\/span> <\/span>{\r\n    list.add(<span class=\"hljs-keyword\">null<\/span>);  <span class=\"hljs-comment\">\/\/ This is valid<\/span>\r\n    <span class=\"hljs-comment\">\/\/ list.add(new Object());  \/\/ This would be a compile-time error<\/span>\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Comparing Bounded and Unbounded Wildcards<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both bounded and unbounded wildcards offer flexibility in dealing with generics in Java. However, they serve different purposes and are best suited for different scenarios. Let&#8217;s dissect the differences and delve into practical scenarios where each might be the preferred choice.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Bounded Wildcards:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Purpose<\/strong>: Bounded wildcards (both upper and lower bounded) are used when you have some knowledge about the type parameter and want to restrict it to a certain range of types.<\/li>\n\n\n\n<li><strong>Advantages<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Ensures type safety by constraining the type parameter.<\/li>\n\n\n\n<li>Provides flexibility within the specified bounds.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Practical Scenarios<\/strong>:\n<ul class=\"wp-block-list\">\n<li><strong>Upper Bounded Wildcards (<code>extends<\/code>)<\/strong>: When you need to read items from a structure and use methods defined in the upper bound. For instance, reading numbers from a list and performing arithmetic operations.<\/li>\n\n\n\n<li><strong>Lower Bounded Wildcards (<code>super<\/code>)<\/strong>: Useful when you need to insert items into a structure. For example, when inserting elements into a list where you want to ensure that the list can hold the type of element you&#8217;re inserting.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\">Unbounded Wildcards:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Purpose<\/strong>: The unbounded wildcard denotes an unknown type. It&#8217;s typically used when you want to work with objects in a generic way without needing specifics about their type.<\/li>\n\n\n\n<li><strong>Advantages<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Maximizes flexibility as it can represent any type.<\/li>\n\n\n\n<li>Bridges the gap between generic and non-generic code.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Practical Scenarios<\/strong>:\n<ul class=\"wp-block-list\">\n<li><strong>General-purpose methods<\/strong>: Useful for methods that can work with any type, like printing elements of a list or clearing its contents.<\/li>\n\n\n\n<li><strong>Interacting with raw types<\/strong>: In legacy code, you might come across raw types. Unbounded wildcards can help smooth interactions between raw types and generic methods.<\/li>\n\n\n\n<li><strong>When type specifics don&#8217;t matter<\/strong>: For instance, if you just want to count the number of items, reset a collection, or test if an item exists in a collection.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\">Choosing One Over the Other:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>For Read-Only Operations<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Use an <strong>upper bounded wildcard<\/strong> if you are reading items from a structure and need to invoke methods defined in its upper bound.<\/li>\n\n\n\n<li>Use an <strong>unbounded wildcard<\/strong> if you&#8217;re reading items but don&#8217;t care about their specific type.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>For Write Operations<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Use a <strong>lower bounded wildcard<\/strong> if you&#8217;re inserting items and want to ensure type safety.<\/li>\n\n\n\n<li>Generally, avoid using unbounded wildcards for writes, as you don&#8217;t have information about the type.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>For Maximum Flexibility<\/strong>: An unbounded wildcard provides the most flexibility but comes at the cost of losing type-specific operations.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">In essence, the choice between bounded and unbounded wildcards boils down to your specific needs. If type safety within certain constraints is paramount, bounded wildcards are your best bet. For operations that are truly type-agnostic, unbounded wildcards shine. Always ensure you maintain a balance between flexibility and type safety, choosing the wildcard that aligns best with the operations you intend to perform.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Generic Erasure<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One of the fundamental aspects of Java generics that often surprises newcomers is the concept of type erasure. In essence, generics are a compile-time construct, meaning that most generic type information is removed when the code is translated to bytecode.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Understanding Type Erasure in Java:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Java generics were introduced in Java 5 to improve type safety and to provide more robust type checking at compile time. However, the designers wanted to ensure backward compatibility with existing non-generic code. To achieve this, they introduced generics in such a way that the bytecode remains the same whether you&#8217;re using raw types or generics. This is facilitated through a mechanism called <strong>type erasure<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">During the compilation process:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The compiler checks the code for correct use of generics and inserts type casts where necessary.<\/li>\n\n\n\n<li>It then removes (or &#8220;erases&#8221;) all the generic type information, replacing it with raw types.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Code Examples: Before and After Type Erasure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Before Type Erasure<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Box<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-keyword\">private<\/span> T value;\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Box<\/span><span class=\"hljs-params\">(T value)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.value = value;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> T <span class=\"hljs-title\">getValue<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> value;\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>After Type Erasure<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Box<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">private<\/span> Object value;\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Box<\/span><span class=\"hljs-params\">(Object value)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.value = value;\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Object <span class=\"hljs-title\">getValue<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> value;\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Notice how the generic type <code>T<\/code> has been replaced with <code>Object<\/code> post type erasure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Limitations and Implications of Type Erasure:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>No Runtime Type Information<\/strong>: Because of type erasure, generic type information is unavailable at runtime. This means that you cannot use reflection to find out the actual type argument of a generic type.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-22\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;String&gt; strings = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\n<span class=\"hljs-keyword\">if<\/span> (strings <span class=\"hljs-keyword\">instanceof<\/span> List&lt;String&gt;) {  <span class=\"hljs-comment\">\/\/ Compile-time error<\/span>\r\n    <span class=\"hljs-comment\">\/\/ Cannot perform instanceof check with parameterized types.<\/span>\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Cannot Create Instances of Type Parameters<\/strong>: You can&#8217;t instantiate an object of a type parameter since it&#8217;s erased at runtime.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-23\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> &lt;T&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">createInstance<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n    T obj = <span class=\"hljs-keyword\">new<\/span> T();  <span class=\"hljs-comment\">\/\/ Compile-time error<\/span>\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-23\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Limitations with Overloaded Methods<\/strong>: Overloading methods based on generic types can lead to issues because of type erasure. After erasure, overloaded methods can have the same raw type, leading to a compile-time error.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-24\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">process<\/span><span class=\"hljs-params\">(List&lt;String&gt; list)<\/span> <\/span>{ ... }\r\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">process<\/span><span class=\"hljs-params\">(List&lt;Integer&gt; list)<\/span> <\/span>{ ... }  <span class=\"hljs-comment\">\/\/ Compile-time error due to type erasure<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-24\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Casts Are Inserted<\/strong>: The compiler inserts casts in the bytecode where needed. This means that even though you&#8217;re not explicitly casting objects in your generic code, casts are present in the bytecode.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Backward Compatibility<\/strong>: One of the major benefits of type erasure is that it ensures backward compatibility. Non-generic code written before Java 5 can work seamlessly with generic code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While type erasure has its set of limitations and implications, it&#8217;s a necessary compromise to introduce strong type checking with generics while preserving backward compatibility. Being aware of how type erasure operates can prevent potential pitfalls when working with generics in Java.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Advanced Techniques with Generics<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Recursive Type Bounds<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Recursive type bounds provide the capability for a type to be defined in terms of itself. This is particularly useful in scenarios where a type parameter in a generic class or method is bound by another type that is parameterized by the first type.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Implementing a Self-Comparable Interface:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine a scenario where you&#8217;re building a framework for entities that can compare themselves to objects of their own type. Here&#8217;s how recursive type bounds come into play:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Self-Comparable Interface<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-25\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">interface<\/span> <span class=\"hljs-title\">SelfComparable<\/span>&lt;<span class=\"hljs-title\">T<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">SelfComparable<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt;&gt; <\/span>{\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">compareTo<\/span><span class=\"hljs-params\">(T other)<\/span><\/span>;\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-25\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the <code>SelfComparable<\/code> interface, <code>T<\/code> is a type parameter that extends <code>SelfComparable&lt;T&gt;<\/code>. This effectively ensures that any type which claims to be <code>SelfComparable<\/code> must compare itself to its own type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Implementing the Self-Comparable Interface<\/strong>:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s create a <code>Person<\/code> class that implements this interface:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-26\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span> <span class=\"hljs-keyword\">implements<\/span> <span class=\"hljs-title\">SelfComparable<\/span>&lt;<span class=\"hljs-title\">Person<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">final<\/span> String name;\r\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">final<\/span> <span class=\"hljs-keyword\">int<\/span> age;\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Person<\/span><span class=\"hljs-params\">(String name, <span class=\"hljs-keyword\">int<\/span> age)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.name = name;\r\n        <span class=\"hljs-keyword\">this<\/span>.age = age;\r\n    }\r\n\r\n    <span class=\"hljs-meta\">@Override<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">compareTo<\/span><span class=\"hljs-params\">(Person other)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> Integer.compare(<span class=\"hljs-keyword\">this<\/span>.age, other.age);\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-26\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the <code>Person<\/code> class, we&#8217;ve implemented the <code>SelfComparable<\/code> interface specifying <code>Person<\/code> as the type parameter. The <code>compareTo<\/code> method is then implemented to compare <code>Person<\/code> objects based on their age.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-27\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">Person alice = <span class=\"hljs-keyword\">new<\/span> Person(<span class=\"hljs-string\">\"Alice\"<\/span>, <span class=\"hljs-number\">25<\/span>);\r\nPerson bob = <span class=\"hljs-keyword\">new<\/span> Person(<span class=\"hljs-string\">\"Bob\"<\/span>, <span class=\"hljs-number\">30<\/span>);\r\n\r\n<span class=\"hljs-keyword\">int<\/span> comparisonResult = alice.compareTo(bob);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-27\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The recursive type bound <code>T extends SelfComparable&lt;T><\/code> ensures a contract that any class implementing <code>SelfComparable<\/code> will compare itself to instances of its own type, providing type safety. It&#8217;s a powerful technique, especially in library and framework design, to impose certain restrictions on type parameters.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Generic Type Inference<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Java&#8217;s type inference mechanism allows you to invoke a generic method without explicitly specifying the type parameter. The Java compiler will infer the type argument based on the context in which the method is called. This makes code more concise and readable.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Leveraging Type Inference in Java:<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Utility Method:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a utility method that determines the middle item in an array:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-28\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Utils<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T&gt; <span class=\"hljs-function\">T <span class=\"hljs-title\">middle<\/span><span class=\"hljs-params\">(T&#91;] array)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> array&#91;array.length \/ <span class=\"hljs-number\">2<\/span>];\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-28\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Using Explicit Type Argument:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Traditionally, before type inference became widely used, you would have to specify the type argument when invoking this method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-29\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">String&#91;] names = {<span class=\"hljs-string\">\"Alice\"<\/span>, <span class=\"hljs-string\">\"Bob\"<\/span>, <span class=\"hljs-string\">\"Charlie\"<\/span>, <span class=\"hljs-string\">\"David\"<\/span>, <span class=\"hljs-string\">\"Eve\"<\/span>};\r\nString middleName = Utils.&lt;String&gt;middle(names);\r\nSystem.out.println(middleName);  <span class=\"hljs-comment\">\/\/ Outputs: Charlie<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-29\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Leveraging Type Inference:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">With type inference, the Java compiler is smart enough to infer the type argument from the context. This means you can omit the type argument:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-30\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">String middleNameInferred = Utils.middle(names);\r\nSystem.out.println(middleNameInferred);  <span class=\"hljs-comment\">\/\/ Outputs: Charlie<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-30\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Inference in Java 7+:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Starting from Java 7, the diamond operator (<code>&lt;&gt;<\/code>) was introduced to further leverage type inference during the instantiation of generic classes:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-31\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List&lt;String&gt; list = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();  <span class=\"hljs-comment\">\/\/ No need to specify \"String\" in the diamond<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-31\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here, the compiler infers the type argument <code>String<\/code> from the variable&#8217;s type (<code>List&lt;String&gt;<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Generic type inference is one of the features that contributes to the elegance and readability of Java code. The compiler&#8217;s capability to infer types from the context reduces redundancy and keeps the code concise. Always make use of type inference when possible to make your code more readable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Generic Factories<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Factories are a key design pattern in object-oriented programming, allowing for the encapsulation of object creation. When combined with generics, factory patterns become even more powerful, as they can produce objects of a generic type based on the provided type argument. This ensures type safety while retaining the flexibility that factories offer.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Factory Patterns with Generics:<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Generic Factory Interface:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s begin by creating a generic interface for our factory:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-32\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">interface<\/span> <span class=\"hljs-title\">Factory<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-function\">T <span class=\"hljs-title\">create<\/span><span class=\"hljs-params\">()<\/span><\/span>;\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-32\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Concrete Implementations:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we&#8217;ll make concrete implementations of this factory for different types:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-33\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Car<\/span> <\/span>{\r\n    <span class=\"hljs-comment\">\/\/ Some attributes and methods for Car<\/span>\r\n}\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">CarFactory<\/span> <span class=\"hljs-keyword\">implements<\/span> <span class=\"hljs-title\">Factory<\/span>&lt;<span class=\"hljs-title\">Car<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-meta\">@Override<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Car <span class=\"hljs-title\">create<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">new<\/span> Car();\r\n    }\r\n}\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Bike<\/span> <\/span>{\r\n    <span class=\"hljs-comment\">\/\/ Some attributes and methods for Bike<\/span>\r\n}\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">BikeFactory<\/span> <span class=\"hljs-keyword\">implements<\/span> <span class=\"hljs-title\">Factory<\/span>&lt;<span class=\"hljs-title\">Bike<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-meta\">@Override<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Bike <span class=\"hljs-title\">create<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">new<\/span> Bike();\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-33\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Using the Factory:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">With the factories in place, you can create objects of <code>Car<\/code> and <code>Bike<\/code> using their respective factory classes:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-34\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">Factory&lt;Car&gt; carFactory = <span class=\"hljs-keyword\">new<\/span> CarFactory();\r\nCar car = carFactory.create();\r\n\r\nFactory&lt;Bike&gt; bikeFactory = <span class=\"hljs-keyword\">new<\/span> BikeFactory();\r\nBike bike = bikeFactory.create();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-34\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Generic Factory Utility:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">We can further leverage generics to create a factory utility class that can produce any object given its class type:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-35\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">GenericFactory<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <span class=\"hljs-keyword\">implements<\/span> <span class=\"hljs-title\">Factory<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-keyword\">private<\/span> Class&lt;T&gt; clazz;\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">GenericFactory<\/span><span class=\"hljs-params\">(Class&lt;T&gt; clazz)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">this<\/span>.clazz = clazz;\r\n    }\r\n\r\n    <span class=\"hljs-meta\">@Override<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> T <span class=\"hljs-title\">create<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">try<\/span> {\r\n            <span class=\"hljs-keyword\">return<\/span> clazz.newInstance();\r\n        } <span class=\"hljs-keyword\">catch<\/span> (InstantiationException | IllegalAccessException e) {\r\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> RuntimeException(<span class=\"hljs-string\">\"Could not instantiate object\"<\/span>, e);\r\n        }\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-35\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Using the Generic Factory Utility:<\/h5>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-36\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">Factory&lt;Car&gt; genericCarFactory = <span class=\"hljs-keyword\">new<\/span> GenericFactory&lt;&gt;(Car<span class=\"hljs-class\">.<span class=\"hljs-keyword\">class<\/span>)<\/span>;\r\nCar anotherCar = genericCarFactory.create();\r\n\r\nFactory&lt;Bike&gt; genericBikeFactory = <span class=\"hljs-keyword\">new<\/span> GenericFactory&lt;&gt;(Bike<span class=\"hljs-class\">.<span class=\"hljs-keyword\">class<\/span>)<\/span>;\r\nBike anotherBike = genericBikeFactory.create();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-36\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">With generic factories, we&#8217;ve combined the type-safety and flexibility of generics with the encapsulation and control of the factory pattern. This pattern becomes particularly useful in scenarios where the exact type to instantiate might vary, such as plugin architectures or dependency injection frameworks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Pitfalls and Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When working with generics in Java, while the advantages are many, there are certain pitfalls developers need to be wary of. Alongside these pitfalls, it&#8217;s essential to be aware of best practices that can ensure robust and maintainable code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mixing Raw Types and Generics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Pitfall<\/strong>: One common mistake is using raw types (e.g., <code>List<\/code> instead of <code>List&lt;String&gt;<\/code>) in the codebase that uses generics. This defeats the purpose of generics and risks introducing ClassCastException at runtime.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Best Practice<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Always specify type parameters when using generic classes or methods, even if it means using wildcard (<code>?<\/code>).<\/li>\n\n\n\n<li>Do not ignore or suppress unchecked warnings. They&#8217;re an indicator that you might be using raw types or making other unsafe operations.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-37\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">List rawList = <span class=\"hljs-keyword\">new<\/span> ArrayList();\r\nrawList.add(<span class=\"hljs-string\">\"test\"<\/span>);\r\nInteger num = (Integer) rawList.get(<span class=\"hljs-number\">0<\/span>);  <span class=\"hljs-comment\">\/\/ Throws ClassCastException at runtime<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-37\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Avoiding Overuse of Generics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Pitfall<\/strong>: Overusing generics or creating overly complicated generic types can make the code hard to read and maintain.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Best Practice<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use generics where it provides a clear benefit in type safety or code reuse.<\/li>\n\n\n\n<li>Avoid creating deeply nested or overly complicated generic types.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example of Overcomplication<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-38\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-comment\">\/\/ Overly complex generic type<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Node<\/span>&lt;<span class=\"hljs-title\">T<\/span>, <span class=\"hljs-title\">U<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Comparable<\/span>&lt;<span class=\"hljs-title\">U<\/span>&gt;, <span class=\"hljs-title\">V<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Serializable<\/span> &amp; <span class=\"hljs-title\">Runnable<\/span>&gt; <\/span>{ ... }<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-38\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">7.3 Tips for Writing Robust Generic Code<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Favor Generic Methods<\/strong>: Even if you&#8217;re not writing a generic class, consider using generic methods if they provide type safety and flexibility.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-39\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">printArray<\/span><span class=\"hljs-params\">(T&#91;] arr)<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">for<\/span> (T item : arr) {\r\n        System.out.println(item);\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-39\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Use Bounded Wildcards for Flexibility<\/strong>: If you&#8217;re writing methods that do not depend on the actual type parameter, but only need to ensure some level of type compatibility, use bounded wildcards (<code>? extends<\/code> or <code>? super<\/code>).<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-40\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">copyData<\/span><span class=\"hljs-params\">(List&lt;? extends Number&gt; src, List&lt;? <span class=\"hljs-keyword\">super<\/span> Number&gt; dest)<\/span> <\/span>{\r\n    dest.addAll(src);\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-40\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Avoid Mutable Static Fields with Generic Types<\/strong>: This can introduce type safety issues, especially when dealing with raw types.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Be Aware of Type Erasure<\/strong>: Understand that generic type information is erased at runtime. Avoid scenarios where runtime type information is crucial.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Always Document Your Code<\/strong>: If you&#8217;re writing a generic class or method that will be used by others, provide clear JavaDoc comments explaining how the generics work and any constraints on the type parameters.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Generic&#8217;s Limitations and Workarounds<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Cannot Instantiate Generic Types with Primitive Types<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java, generics work with reference types, not primitive types. This means you cannot directly use primitive types (<code>int<\/code>, <code>char<\/code>, <code>boolean<\/code>, etc.) as generic type arguments. Instead, you need to use the corresponding wrapper classes (<code>Integer<\/code>, <code>Character<\/code>, <code>Boolean<\/code>, etc.).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Using Wrappers Instead of Primitives:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example of Incorrect Usage<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-41\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-comment\">\/\/ The following code will produce a compile-time error<\/span>\r\n<span class=\"hljs-comment\">\/\/ List&lt;int&gt; numbers = new ArrayList&lt;int&gt;();<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-41\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The above example attempts to use the primitive type <code>int<\/code> as a type argument for the <code>List<\/code> interface, which will result in a compilation error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Corrected Version using Wrapper Classes<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-42\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-comment\">\/\/ Use the Integer wrapper class instead of the int primitive type<\/span>\r\nList&lt;Integer&gt; numbers = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\nnumbers.add(<span class=\"hljs-number\">1<\/span>);\r\nnumbers.add(<span class=\"hljs-number\">2<\/span>);\r\nnumbers.add(<span class=\"hljs-number\">3<\/span>);\r\n\r\n<span class=\"hljs-keyword\">for<\/span> (Integer num : numbers) {\r\n    System.out.println(num);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-42\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the corrected version, we use the <code>Integer<\/code> wrapper class, allowing us to store integers in our generic <code>List<\/code>. The Java compiler and the Java Virtual Machine (JVM) handle the conversion between the primitive <code>int<\/code> type and its wrapper class <code>Integer<\/code> using a feature known as autoboxing and unboxing.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Benefit of Using Wrapper Classes:<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Allows the use of primitive values in generic data structures and methods.<\/li>\n\n\n\n<li>Provides a range of utility methods (like <code>Integer.parseInt(...)<\/code>) that aren&#8217;t available with the primitive counterparts.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Points to Consider:<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Wrapper classes use more memory than primitive types, so there&#8217;s a trade-off between memory usage and the benefits of using generics.<\/li>\n\n\n\n<li>Autoboxing and unboxing introduce a minor performance overhead compared to using primitives directly.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">When working with generics in Java, always remember that primitive types cannot be used as type arguments. Using the corresponding wrapper classes ensures type safety and allows you to leverage the full power of Java&#8217;s generics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Static Fields and Methods in Generics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java, static fields and methods are associated with a class, not with any particular instance of the class. When it comes to generics, this poses a problem, because type parameters are linked with instances, not with the class itself. As such, the class doesn&#8217;t &#8220;know&#8221; about the specific generic type until an instance is created.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Why static fields of type parameter aren&#8217;t allowed<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Type Erasure<\/strong>: Generics in Java use type erasure to implement generic behavior. This means that at runtime, the JVM doesn&#8217;t actually know about the generic types \u2014 a <code>List&lt;String><\/code> and a <code>List&lt;Integer><\/code> are just <code>List<\/code> objects as far as the bytecode is concerned. This makes it impossible for static fields to &#8220;remember&#8221; their generic type, as there&#8217;s no type information available at runtime.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Shared Among All Instances<\/strong>: Static fields are shared among all instances of a class, regardless of their type parameters. If static fields could be parameterized with type arguments, it would lead to ambiguity. Consider the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-43\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Container<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <\/span>{\r\n    <span class=\"hljs-comment\">\/\/ Hypothetically, if this were allowed...<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> T data;\r\n}\r\n\r\nContainer&lt;String&gt; stringContainer;\r\nContainer&lt;Integer&gt; integerContainer;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-43\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">How would Java handle <code>Container.data<\/code>? Is it a String? An Integer? This ambiguity makes it impossible for static fields to be parameterized by type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>No Instance-Specific Information<\/strong>: Since static context doesn&#8217;t have access to instance-specific information, there&#8217;s no way to ensure the type safety of a generic type parameter. This would break the primary goal of generics, which is to ensure type safety at compile time.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Workarounds<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Even though you can&#8217;t have static fields of a generic type, you can have static methods that use generic types. However, the generic type parameter for these static methods is typically defined within the method signature itself and is independent of the class&#8217;s type parameter.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-44\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Utility<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(T item)<\/span> <\/span>{\r\n        System.out.println(item);\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-44\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above example, the method <code>print<\/code> is a generic method that accepts any type of argument and prints it. The type parameter <code>&lt;T&gt;<\/code> is specified and scoped only for that method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In essence, while Java&#8217;s generic system provides a strong mechanism for type-safe operations at the instance level, certain static features remain inherently non-generic due to the way the language and runtime environment are designed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exception Handling with Generics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java, exceptions have their own type hierarchy and are used to handle and indicate various types of exceptional conditions that might occur during the execution of the program. However, when it comes to generics, there are some constraints and limitations that need to be understood, particularly when we consider the combination of generics with exceptions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Challenges with Generic Exceptions:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Generic Exception Classes Are Not Allowed<\/strong>: Java does not allow you to directly create a generic exception class. This is because of the type erasure mechanism, which removes generic type information at runtime. If Java allowed generic exceptions, the runtime system wouldn&#8217;t be able to differentiate between different types of the generic exception.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-45\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-comment\">\/\/ This will result in a compile-time error<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">GenericException<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Exception<\/span> <\/span>{ }<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-45\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Casting Generic Types Can Lead to Hidden RuntimeExceptions<\/strong>: If you try to work around the aforementioned limitation by casting, you risk introducing runtime exceptions like <code>ClassCastException<\/code>, which somewhat defeats the purpose of generics in providing compile-time type safety.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Workaround:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Though you can&#8217;t create generic exception classes, you can still create generic methods that throw exceptions. Moreover, you can use generic information in the construction of an exception message or in exception handling logic:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-46\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ExceptionUtils<\/span> <\/span>{\r\n    \r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T extends Exception&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">handleException<\/span><span class=\"hljs-params\">(T exception, String additionalMessage)<\/span> <span class=\"hljs-keyword\">throws<\/span> T <\/span>{\r\n        System.err.println(<span class=\"hljs-string\">\"Handled exception of type: \"<\/span> + exception.getClass().getName());\r\n        System.err.println(<span class=\"hljs-string\">\"Message: \"<\/span> + exception.getMessage());\r\n        System.err.println(<span class=\"hljs-string\">\"Additional Info: \"<\/span> + additionalMessage);\r\n        \r\n        <span class=\"hljs-keyword\">throw<\/span> exception;\r\n    }\r\n    \r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">(String&#91;] args)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">try<\/span> {\r\n            ExceptionUtils.handleException(<span class=\"hljs-keyword\">new<\/span> IOException(<span class=\"hljs-string\">\"File not found\"<\/span>), <span class=\"hljs-string\">\"Please check the file path.\"<\/span>);\r\n        } <span class=\"hljs-keyword\">catch<\/span> (IOException e) {\r\n            <span class=\"hljs-comment\">\/\/ Handle the IOException<\/span>\r\n        }\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-46\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above code, we have a utility method <code>handleException<\/code> that can handle exceptions of any type derived from <code>Exception<\/code>. It logs some details and then re-throws the exception, allowing it to be caught by appropriate catch blocks in the calling code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While generics offer a lot of flexibility and type safety in many areas of Java programming, exception handling remains an area where generics have inherent limitations. However, with a deep understanding of Java&#8217;s type system, developers can still find ways to achieve the desired functionality with a bit of creativity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practical Applications of Generics<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Generics in Java Collections Framework<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Java Collections Framework is a suite of interfaces and classes that provide a unified architecture for representing and manipulating collections. With the introduction of generics in Java 5, the Collections Framework was re-engineered to incorporate generics, which enhanced type safety and reduced runtime errors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s explore how generics are used in some of the core components of the Collections Framework:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">ArrayList:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">An <code>ArrayList<\/code> is a resizable array that implements the <code>List<\/code> interface. It allows you to store elements in a linear fashion and provides random access to them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Without Generics<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-47\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">ArrayList list = <span class=\"hljs-keyword\">new<\/span> ArrayList();\r\nlist.add(<span class=\"hljs-string\">\"test\"<\/span>);\r\nlist.add(<span class=\"hljs-number\">123<\/span>);  <span class=\"hljs-comment\">\/\/ This is valid, but can lead to runtime errors later<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-47\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>With Generics<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-48\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">ArrayList&lt;String&gt; list = <span class=\"hljs-keyword\">new<\/span> ArrayList&lt;&gt;();\r\nlist.add(<span class=\"hljs-string\">\"test\"<\/span>);\r\n<span class=\"hljs-comment\">\/\/ list.add(123);  \/\/ This will give a compile-time error, which is what we want<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-48\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\">HashMap:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>HashMap<\/code> is an implementation of the <code>Map<\/code> interface, which maps keys to values. It allows constant-time performance for basic operations (get and put), assuming the hash function disperses the elements properly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Without Generics<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-49\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">HashMap map = <span class=\"hljs-keyword\">new<\/span> HashMap();\r\nmap.put(<span class=\"hljs-string\">\"key\"<\/span>, <span class=\"hljs-string\">\"value\"<\/span>);\r\nString value = (String) map.get(<span class=\"hljs-string\">\"key\"<\/span>);  <span class=\"hljs-comment\">\/\/ Casting required<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-49\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>With Generics<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-50\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">HashMap&lt;String, String&gt; map = <span class=\"hljs-keyword\">new<\/span> HashMap&lt;&gt;();\r\nmap.put(<span class=\"hljs-string\">\"key\"<\/span>, <span class=\"hljs-string\">\"value\"<\/span>);\r\nString value = map.get(<span class=\"hljs-string\">\"key\"<\/span>);  <span class=\"hljs-comment\">\/\/ No casting required<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-50\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\">HashSet:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>HashSet<\/code> is a collection that does not allow duplicate elements. It implements the <code>Set<\/code> interface and is backed by a <code>HashMap<\/code> instance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Without Generics<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-51\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">HashSet set = <span class=\"hljs-keyword\">new<\/span> HashSet();\r\nset.add(<span class=\"hljs-string\">\"element\"<\/span>);\r\n<span class=\"hljs-comment\">\/\/ set.add(123);  \/\/ Can add any type, but can lead to issues later<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-51\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>With Generics<\/strong>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-52\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\">HashSet&lt;String&gt; set = <span class=\"hljs-keyword\">new<\/span> HashSet&lt;&gt;();\r\nset.add(<span class=\"hljs-string\">\"element\"<\/span>);\r\n<span class=\"hljs-comment\">\/\/ set.add(123);  \/\/ Compile-time error<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-52\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\">Best Practices:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Always Specify Type Arguments<\/strong>: While it&#8217;s possible to create raw types (i.e., without specifying type arguments), doing so is discouraged because you&#8217;ll lose the benefits of type safety.<\/li>\n\n\n\n<li><strong>Use Diamond Operator<\/strong>: Starting from Java 7, you can use the diamond operator (<code>&lt;&gt;<\/code>) while creating an instance, and the compiler will infer the type arguments from the context.<\/li>\n\n\n\n<li><strong>Avoid Using Raw Types<\/strong>: Using raw types in new code is considered bad practice. It can lead to issues that manifest as runtime errors instead of compile-time errors.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Designing Generic Algorithms<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Designing generic algorithms means writing methods or algorithms that can work across different data types while maintaining type safety. This allows the same algorithm to be reused across various data structures or data types without requiring a specific implementation for each type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s dive into how we can implement a generic sorting algorithm, specifically the Bubble Sort, as it&#8217;s easy to understand and implement.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Generic Bubble Sort:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Bubble Sort is a simple sorting algorithm that works by repeatedly stepping through the list, comparing each pair of adjacent items, and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates the list is sorted.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-53\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">GenericBubbleSort<\/span> <\/span>{\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> &lt;T extends Comparable&lt;T&gt;&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">sort<\/span><span class=\"hljs-params\">(T&#91;] array)<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">int<\/span> n = array.length;\r\n        <span class=\"hljs-keyword\">boolean<\/span> swapped;\r\n\r\n        <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; n - <span class=\"hljs-number\">1<\/span>; i++) {\r\n            swapped = <span class=\"hljs-keyword\">false<\/span>;\r\n            <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> j = <span class=\"hljs-number\">0<\/span>; j &lt; n - i - <span class=\"hljs-number\">1<\/span>; j++) {\r\n                <span class=\"hljs-keyword\">if<\/span> (array&#91;j].compareTo(array&#91;j + <span class=\"hljs-number\">1<\/span>]) &gt; <span class=\"hljs-number\">0<\/span>) {\r\n                    <span class=\"hljs-comment\">\/\/ swap array&#91;j] and array&#91;j+1]<\/span>\r\n                    T temp = array&#91;j];\r\n                    array&#91;j] = array&#91;j + <span class=\"hljs-number\">1<\/span>];\r\n                    array&#91;j + <span class=\"hljs-number\">1<\/span>] = temp;\r\n\r\n                    swapped = <span class=\"hljs-keyword\">true<\/span>;\r\n                }\r\n            }\r\n\r\n            <span class=\"hljs-comment\">\/\/ If no two elements were swapped in inner loop, the array is sorted<\/span>\r\n            <span class=\"hljs-keyword\">if<\/span> (!swapped) <span class=\"hljs-keyword\">break<\/span>;\r\n        }\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">(String&#91;] args)<\/span> <\/span>{\r\n        Integer&#91;] numbers = {<span class=\"hljs-number\">64<\/span>, <span class=\"hljs-number\">34<\/span>, <span class=\"hljs-number\">25<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">22<\/span>, <span class=\"hljs-number\">11<\/span>, <span class=\"hljs-number\">90<\/span>};\r\n        sort(numbers);\r\n        System.out.println(Arrays.toString(numbers));\r\n\r\n        String&#91;] words = {<span class=\"hljs-string\">\"apple\"<\/span>, <span class=\"hljs-string\">\"banana\"<\/span>, <span class=\"hljs-string\">\"cherry\"<\/span>, <span class=\"hljs-string\">\"date\"<\/span>, <span class=\"hljs-string\">\"elderberry\"<\/span>};\r\n        sort(words);\r\n        System.out.println(Arrays.toString(words));\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-53\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Points to Note<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The generic method <code>sort<\/code> uses a type parameter <code>T<\/code> which extends <code>Comparable&lt;T&gt;<\/code>. This means the type <code>T<\/code> must be comparable with other objects of its own type. The <code>compareTo<\/code> method is a part of the <code>Comparable<\/code> interface, and many Java built-in types like <code>String<\/code>, <code>Integer<\/code>, etc., already implement this interface.<\/li>\n\n\n\n<li>The algorithm will work for any array of a type that implements <code>Comparable<\/code>, be it strings, integers, custom objects, etc.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Reusability<\/strong>: The same generic method can be used to sort arrays of different types.<\/li>\n\n\n\n<li><strong>Type Safety<\/strong>: The compiler checks for type compatibility at compile-time, reducing runtime errors.<\/li>\n\n\n\n<li><strong>Code Reduction<\/strong>: No need to write separate sorting methods for each data type.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Using Generics in Custom Data Structures<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Using generics in custom data structures enables them to store any data type while ensuring compile-time type safety. It also ensures reusability and maintainability of the code. Let&#8217;s look at how we can build a generic LinkedList in Java.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Generic LinkedList:<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A LinkedList consists of nodes, where each node contains data and a reference (or link) to the next node in the sequence. Here, we&#8217;ll implement a singly linked list.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-54\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">GenericLinkedList<\/span>&lt;<span class=\"hljs-title\">T<\/span>&gt; <\/span>{\r\n    \r\n    <span class=\"hljs-comment\">\/\/ Node inner class<\/span>\r\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Node<\/span> <\/span>{\r\n        T data;\r\n        Node next;\r\n\r\n        Node(T data) {\r\n            <span class=\"hljs-keyword\">this<\/span>.data = data;\r\n            <span class=\"hljs-keyword\">this<\/span>.next = <span class=\"hljs-keyword\">null<\/span>;\r\n        }\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">private<\/span> Node head = <span class=\"hljs-keyword\">null<\/span>;\r\n\r\n    <span class=\"hljs-comment\">\/\/ Method to add a new node at the end<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">add<\/span><span class=\"hljs-params\">(T data)<\/span> <\/span>{\r\n        Node newNode = <span class=\"hljs-keyword\">new<\/span> Node(data);\r\n        <span class=\"hljs-keyword\">if<\/span> (head == <span class=\"hljs-keyword\">null<\/span>) {\r\n            head = newNode;\r\n            <span class=\"hljs-keyword\">return<\/span>;\r\n        }\r\n\r\n        Node current = head;\r\n        <span class=\"hljs-keyword\">while<\/span> (current.next != <span class=\"hljs-keyword\">null<\/span>) {\r\n            current = current.next;\r\n        }\r\n        current.next = newNode;\r\n    }\r\n\r\n    <span class=\"hljs-comment\">\/\/ Method to print the linked list<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">printList<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n        Node current = head;\r\n        <span class=\"hljs-keyword\">while<\/span> (current != <span class=\"hljs-keyword\">null<\/span>) {\r\n            System.out.print(current.data + <span class=\"hljs-string\">\" -&gt; \"<\/span>);\r\n            current = current.next;\r\n        }\r\n        System.out.println(<span class=\"hljs-string\">\"null\"<\/span>);\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">(String&#91;] args)<\/span> <\/span>{\r\n        GenericLinkedList&lt;String&gt; stringList = <span class=\"hljs-keyword\">new<\/span> GenericLinkedList&lt;&gt;();\r\n        stringList.add(<span class=\"hljs-string\">\"Node1\"<\/span>);\r\n        stringList.add(<span class=\"hljs-string\">\"Node2\"<\/span>);\r\n        stringList.printList();\r\n\r\n        GenericLinkedList&lt;Integer&gt; intList = <span class=\"hljs-keyword\">new<\/span> GenericLinkedList&lt;&gt;();\r\n        intList.add(<span class=\"hljs-number\">1<\/span>);\r\n        intList.add(<span class=\"hljs-number\">2<\/span>);\r\n        intList.add(<span class=\"hljs-number\">3<\/span>);\r\n        intList.printList();\r\n    }\r\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-54\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Points to Note<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The <code>GenericLinkedList<\/code> class has a type parameter <code>T<\/code>, which means the linked list can store data of any type.<\/li>\n\n\n\n<li>The inner <code>Node<\/code> class also uses the type parameter <code>T<\/code> to define the data type of each node.<\/li>\n\n\n\n<li>The <code>add<\/code> method allows adding nodes of type <code>T<\/code> to the list.<\/li>\n\n\n\n<li>The <code>printList<\/code> method prints the data of each node in the list.<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Flexibility<\/strong>: You can create linked lists of any data type without needing separate implementations.<\/li>\n\n\n\n<li><strong>Type Safety<\/strong>: Using generics ensures that the data type of the linked list is checked at compile time, preventing potential type mismatches or casting issues at runtime.<\/li>\n\n\n\n<li><strong>Cleaner Code<\/strong>: The use of generics results in cleaner and more understandable code, as it abstracts away type-specific details.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Similarly, you can extend this concept to build other generic data structures like Trees, Stacks, Queues, etc. Incorporating generics makes custom data structures more versatile and adaptable to various application needs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As we wrap up, it&#8217;s crucial to realize the transformative impact generics can bring to your Java projects. By incorporating generics, you&#8217;re not only ensuring type-safety but also significantly enhancing code reusability and maintainability. Java Generics empowers developers to write more generic, type-safe, and efficient code that stands the test of evolving requirements and growing codebases.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Java has undergone numerous evolutions since its inception in the mid-&#8217;90s. Its adaptability and commitment to improvement have been some of the pivotal reasons for its widespread adoption. One such significant improvement was the introduction of Generics in Java 5.0. Brief History and Need for Java Generics Before the arrival of Generics, Java developers [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[5,4],"tags":[],"class_list":["post-1022","post","type-post","status-publish","format-standard","category-java","category-programming-languages","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Mastering Java Generics: From Basic to Advanced<\/title>\n<meta name=\"description\" content=\"The addition of Generics in Java allowed developers to provide a type parameter to collections, ensuring type safety.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Mastering Java Generics: From Basic to Advanced\" \/>\n<meta property=\"og:description\" content=\"The addition of Generics in Java allowed developers to provide a type parameter to collections, ensuring type safety.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-24T01:37:23+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-08-24T01:37:27+00:00\" \/>\n<meta name=\"author\" content=\"w3compadmin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"w3compadmin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"24 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/\"},\"author\":{\"name\":\"w3compadmin\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"headline\":\"Mastering Java Generics: From Basic to Advanced\",\"datePublished\":\"2023-08-24T01:37:23+00:00\",\"dateModified\":\"2023-08-24T01:37:27+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/\"},\"wordCount\":5342,\"commentCount\":0,\"articleSection\":[\"Java\",\"Programming Languages\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/\",\"name\":\"Mastering Java Generics: From Basic to Advanced\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\"},\"datePublished\":\"2023-08-24T01:37:23+00:00\",\"dateModified\":\"2023-08-24T01:37:27+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"description\":\"The addition of Generics in Java allowed developers to provide a type parameter to collections, ensuring type safety.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/java-generics-basic-advanced\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Articles Home\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Programming Languages\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/programming-languages\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Mastering Java Generics: From Basic to Advanced\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\",\"name\":\"Developer Articles Hub\",\"description\":\"\",\"alternateName\":\"Developer Articles\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\",\"name\":\"w3compadmin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"contentUrl\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"caption\":\"w3compadmin\"},\"sameAs\":[\"http:\\\/\\\/w3computing.com\\\/articles\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Mastering Java Generics: From Basic to Advanced","description":"The addition of Generics in Java allowed developers to provide a type parameter to collections, ensuring type safety.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/","og_locale":"en_US","og_type":"article","og_title":"Mastering Java Generics: From Basic to Advanced","og_description":"The addition of Generics in Java allowed developers to provide a type parameter to collections, ensuring type safety.","og_url":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/","article_published_time":"2023-08-24T01:37:23+00:00","article_modified_time":"2023-08-24T01:37:27+00:00","author":"w3compadmin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"w3compadmin","Est. reading time":"24 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/#article","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/"},"author":{"name":"w3compadmin","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"headline":"Mastering Java Generics: From Basic to Advanced","datePublished":"2023-08-24T01:37:23+00:00","dateModified":"2023-08-24T01:37:27+00:00","mainEntityOfPage":{"@id":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/"},"wordCount":5342,"commentCount":0,"articleSection":["Java","Programming Languages"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/","url":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/","name":"Mastering Java Generics: From Basic to Advanced","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/#website"},"datePublished":"2023-08-24T01:37:23+00:00","dateModified":"2023-08-24T01:37:27+00:00","author":{"@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"description":"The addition of Generics in Java allowed developers to provide a type parameter to collections, ensuring type safety.","breadcrumb":{"@id":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.w3computing.com\/articles\/java-generics-basic-advanced\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Articles Home","item":"https:\/\/www.w3computing.com\/articles\/"},{"@type":"ListItem","position":2,"name":"Programming Languages","item":"https:\/\/www.w3computing.com\/articles\/programming-languages\/"},{"@type":"ListItem","position":3,"name":"Mastering Java Generics: From Basic to Advanced"}]},{"@type":"WebSite","@id":"https:\/\/www.w3computing.com\/articles\/#website","url":"https:\/\/www.w3computing.com\/articles\/","name":"Developer Articles Hub","description":"","alternateName":"Developer Articles","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.w3computing.com\/articles\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561","name":"w3compadmin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","url":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","contentUrl":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","caption":"w3compadmin"},"sameAs":["http:\/\/w3computing.com\/articles"]}]}},"featured_image_src":null,"featured_image_src_square":null,"author_info":{"display_name":"w3compadmin","author_link":"https:\/\/www.w3computing.com\/articles\/author\/w3compadmin\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/1022","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/comments?post=1022"}],"version-history":[{"count":31,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/1022\/revisions"}],"predecessor-version":[{"id":1053,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/1022\/revisions\/1053"}],"wp:attachment":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/media?parent=1022"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/categories?post=1022"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/tags?post=1022"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}