{"id":1312,"date":"2022-02-27T18:02:31","date_gmt":"2022-02-27T18:02:31","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1312"},"modified":"2022-02-27T18:02:31","modified_gmt":"2022-02-27T18:02:31","slug":"java-generics","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/27\/java-generics\/","title":{"rendered":"Java Generics"},"content":{"rendered":"\n<p>In this tutorial, we will learn about Java Generics, how to create generics class and methods and its advantages with the help of examples.<\/p>\n\n\n\n<p id=\"introduction\">The Java Generics allows us to create a single class, interface, and method that can be used with different types of data (objects).<\/p>\n\n\n\n<p>This helps us to reuse our code.<\/p>\n\n\n\n<p><strong>Note<\/strong>:&nbsp;<strong>Generics<\/strong>&nbsp;does not work with primitive types (<code>int<\/code>,&nbsp;<code>float<\/code>,&nbsp;<code>char<\/code>, etc).<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"class\">Java Generics Class<\/h2>\n\n\n\n<p>We can create a class that can be used with any type of data. Such a class is known as Generics Class.<\/p>\n\n\n\n<p>Here&#8217;s is how we can create a generics class in Java:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Create a Generics Class<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ initialize generic class\n    \/\/ with Integer data\n    GenericsClass&lt;Integer&gt; intObj = new GenericsClass&lt;&gt;(5);\n    System.out.println(\"Generic Class returns: \" + intObj.getData());\n\n    \/\/ initialize generic class\n    \/\/ with String data\n    GenericsClass&lt;String&gt; stringObj = new GenericsClass&lt;&gt;(\"Java Programming\");\n    System.out.println(\"Generic Class returns: \" + stringObj.getData());\n  }\n}\n\n\/\/ create a generics class\nclass GenericsClass&lt;T&gt; {\n\n  \/\/ variable of T type\n  private T data;\n\n  public GenericsClass(T data) {\n    this.data = data;\n  }\n\n  \/\/ method that return T type variable\n  public T getData() {\n    return this.data;\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Generic Class returns: 5\nGeneric Class returns: Java Programming<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a generic class named&nbsp;<var>GenericsClass<\/var>. This class can be used to work with any type of data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class GenericsClass&lt;T&gt; {...}<\/code><\/pre>\n\n\n\n<p>Here,&nbsp;<var>T<\/var>&nbsp;used inside the angle bracket&nbsp;<code>&lt;&gt;<\/code>&nbsp;indicates the&nbsp;<strong>type parameter<\/strong>. Inside the&nbsp;<code>Main<\/code>&nbsp;class, we have created two objects of&nbsp;<var>GenericsClass<\/var><\/p>\n\n\n\n<ul><li><var>intObj<\/var>&nbsp;&#8211; Here, the type parameter&nbsp;<var>T<\/var>&nbsp;is replaced by&nbsp;<code>Integer<\/code>. Now, the&nbsp;<var>GenericsClass<\/var>&nbsp;works with integer data.<\/li><li><var>stringObj<\/var>&nbsp;&#8211; Here, the type parameter&nbsp;<var>T<\/var>&nbsp;is replaced by&nbsp;<code>String<\/code>. Now, the&nbsp;<var>GenericsClass<\/var>&nbsp;works with string data.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"methods\">Java Generics Method<\/h2>\n\n\n\n<p>Similar to the generics class, we can also create a method that can be used with any type of data. Such a class is known as Generics Method.<\/p>\n\n\n\n<p>Here&#8217;s is how we can create a generics class in Java:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Create a Generics Method<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ initialize the class with Integer data\n    DemoClass demo = new DemoClass();\n\n    \/\/ generics method working with String\n    demo.&lt;String&gt;genericsMethod(\"Java Programming\");\n\n    \/\/ generics method working with integer\n    demo.&lt;Integer&gt;genericsMethod(25);\n  }\n}\n\nclass DemoClass {\n\n  \/\/ creae a generics method\n  public &lt;T&gt; void genericsMethod(T data) {\n    System.out.println(\"Generics Method:\");\n    System.out.println(\"Data Passed: \" + data);\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Generics Method:\nData Passed: Java Programming\nGenerics Method:\nData Passed: 25<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a generic method named&nbsp;<var>genericsMethod<\/var>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public &lt;T&gt; void genericMethod(T data) {...}<\/code><\/pre>\n\n\n\n<p>Here, the type parameter&nbsp;<code>&lt;T&gt;<\/code>&nbsp;is inserted after the modifier&nbsp;<code>public<\/code>&nbsp;and before the return type&nbsp;<code>void<\/code>.<\/p>\n\n\n\n<p>We can call the generics method by placing the actual type&nbsp;<code>&lt;String&gt;<\/code>&nbsp;and&nbsp;<code>&lt;Integer&gt;<\/code>&nbsp;inside the bracket before the method name.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>demo.&lt;String&gt;genericMethod(\"Java Programming\");\n\ndemo.&lt;Integer&gt;genericMethod(25);<\/code><\/pre>\n\n\n\n<p><strong>Note<\/strong>: We can call the generics method without including the type parameter. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>demo.genericsMethod(\"Java Programming\");<\/code><\/pre>\n\n\n\n<p>In this case, the compiler can match the type parameter based on the value passed to the method.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"bounded-types\">Bounded Types<\/h2>\n\n\n\n<p>In general, the&nbsp;<strong>type parameter<\/strong>&nbsp;can accept any data types (except primitive types).<\/p>\n\n\n\n<p>However, if we want to use generics for some specific types (such as accept data of number types) only, then we can use bounded types.<\/p>\n\n\n\n<p>In the case of bound types, we use the&nbsp;<code>extends<\/code>&nbsp;keyword. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;T extends A&gt;<\/code><\/pre>\n\n\n\n<p>This means&nbsp;<var>T<\/var>&nbsp;can only accept data that are subtypes of&nbsp;<var>A<\/var>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Bounded Types<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class GenericsClass &lt;T extends Number&gt; {\n\n  public void display() {\n    System.out.println(\"This is a bounded type generics class.\");\n  }\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ create an object of GenericsClass\n    GenericsClass&lt;String&gt; obj = new GenericsClass&lt;&gt;();\n  }\n}<\/code><\/pre>\n\n\n\n<p>In the above example, we have created a class named GenericsClass. Notice the expression, notice the expression<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;T extends Number&gt; <\/code><\/pre>\n\n\n\n<p>Here,&nbsp;<var>GenericsClass<\/var>&nbsp;is created with bounded type. This means&nbsp;<var>GenericsClass<\/var>&nbsp;can only work with data types that are children of&nbsp;<code>Number<\/code>&nbsp;(<code>Integer<\/code>,&nbsp;<code>Double<\/code>, and so on).<\/p>\n\n\n\n<p>However, we have created an object of the generics class with&nbsp;<code>String<\/code>. In this case, we will get the following error.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>GenericsClass&lt;String&gt; obj = new GenericsClass&lt;&gt;();\n                                                 ^\n    reason: inference variable T has incompatible bounds\n      equality constraints: String\n      lower bounds: Number\n  where T is a type-variable:\n    T extends Number declared in class GenericsClass<\/samp><\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"advantages\">Advantages of Java Generics<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Code Reusability<\/h3>\n\n\n\n<p>With the help of generics in Java, we can write code that will work with different types of data. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public &lt;T&gt; void genericsMethod(T data) {...}<\/code><\/pre>\n\n\n\n<p>Here, we have created a generics method. This same method can be used to perform operations on integer data, string data, and so on.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Compile-time Type Checking<\/h3>\n\n\n\n<p>The&nbsp;<strong>type parameter<\/strong>&nbsp;of generics provides information about the type of data used in the generics code. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ using Generics\nGenericsClass&lt;Integer&gt; list = new GenericsClass&lt;&gt;();<\/code><\/pre>\n\n\n\n<p>Here, we know that&nbsp;<var>GenericsClass<\/var>&nbsp;is working with&nbsp;<code>Integer<\/code>&nbsp;data only.<\/p>\n\n\n\n<p>Now, if we try to pass data other than Integer to this class, the program will generate an error at compile time.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Used with Collections<\/h3>\n\n\n\n<p>The collections framework uses the concept of generics in Java. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ creating a string type ArrayList\nArrayList&lt;String&gt; list1 = new ArrayList&lt;&gt;();\n\n\/\/ creating a integer type ArrayList\nArrayList&lt;Integer&gt; list2 = new ArrayList&lt;&gt;();<\/code><\/pre>\n\n\n\n<p>In the above example, we have used the same&nbsp;<a href=\"https:\/\/www.programiz.com\/java-programming\/arraylist\">ArrayList class<\/a>&nbsp;to work with different types of data.<\/p>\n\n\n\n<p>Similar to&nbsp;<code>ArrayList<\/code>, other collections (<code>LinkedList<\/code>,&nbsp;<code>Queue<\/code>,&nbsp;<code>Maps<\/code>, and so on) are also generic in Java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn about Java Generics, how to create generics class and methods and its advantages with the help of examples. The Java Generics allows us to create a single class, interface, and method that can be used with different types of data (objects). This helps us to reuse our code. Note:&nbsp;Generics&nbsp;does [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[597],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1312"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1312"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1312\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1312"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1312"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1312"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}