JAVA GENERICS
JAVA GENERICS
ADVANTAGES OF GENERICS:
import java.util.ArrayList;
System.out.println(myArrayList);
import java.util.ArrayList;
System.out.println(myArrayList);
The same code produces the Incompatible type error because we can only store the integer
object type.
2. Type-casting not required :
Let's suppose you created an ArrayList(without using Generics), and you want to store
the value at index 0 into an integer variable named "x." Are you allowed to do this in
Java? The answer is a big NO! This is because the ArrayList returns an object, but we're
storing the value in an integer variable. In such cases, we need to type-cast the object into
our desired data type. But, if we use Generics, then there is no need to typecast. Take a
look at the below example to get a better understanding :
import java.util.ArrayList;
int x = myArrayList.get(0);
System.out.println(x);
}
The above code produces an error because we've not typecasted the object into the integer type.
Now, let's typecast and see the results :
import java.util.ArrayList;
System.out.println(x);
10
Now, let's see how we can get the desired results with the help of the Generics :
import java.util.ArrayList;
myArrayList.add(10);
myArrayList.add(20);
myArrayList.add(30);
myArrayList.add(40);
int x = myArrayList.get(0);
System.out.println(x);
10
3. GENERICS IN JAVA EXAMPLE
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
int val;
private T1 t1;
private T2 t2;
this.val = val;
this.t1 = t1;
this.t2= t2;
public T2 getT2() {
return t2;
this.t2 = t2;
}
public int getVal() {
return val;
this.val = val;
public T1 getT1() {
return t1;
this.t1 = t1;
// arrayList.add("str1");
arrayList.add(54);
arrayList.add(643);
// arrayList.add(new Scanner(System.in));
int a = (int) arrayList.get(0);
// System.out.println(a);
System.out.println(str + int1);