Java: What are Generics?
The idea of generics is to allow different types like Integer, String, … etc and user-defined types to be a parameter to methods, classes, and interfaces.
💡 Generics are used for collections
For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any data type.
How to use
We use Angle Bracket parameters
Declare a list containing strings:
List<String> names = new ArrayList<>();
The most commonly used type parameter names are:
- E — Element (used extensively by the Java Collections Framework)
- K — Key
- N — Number
- T — Type
- V — Value
Generic methods
<T> void MyFirstGenericMethod(T element){}T is our generic data type’s name, and when the method is to be called, it would be the same as if T was a typedef for your datatype.
Real Example:
import java.util.*;
public class practice2{
public static void main(String[] args){
Integer[] nums = {1, 2, 3, 4};
Character[] letters = {'a', 'b', 'c', 'd'};
printMe(nums);
printMe(letters);
}
//Generic method
public static <T> void printMe(T[] i){//parameter of t array
// generic for loop where x stores the int, and char
// value stored at every index of array
for(T x : i){
System.out.printf("%s ", x);
}
//space after every printMe
System.out.println();
}
}Generic class, objects, and type members
As another powerful feature of Java, you can also make Generic classes, which are classes that can have members of the generic type.
class Test<T>
{
T obj; // An object of type T is declared
Test(T obj) // parameterized constructor
{
this.obj = obj;
}
public T getObject() // get method
{
return this.obj;
}
}Explanation
- We have declared a class
Testthat can keep theobjof any type. - The constructor
Test(T obj)assigns the value passed as a parameter to data memberobjof typeT. - The get method
T getObject()returns theobjof typeT.
Syntax to instantiate object
To create objects of the generic class, we use the following syntax.
// To create an instance of generic class
Test <DataType> obj = new Test <DataType>();
// We use <> to specify Parameter type
class Test < T > {
T obj;
Test(T obj) {
this.obj = obj;
}
public T getObject() {
return this.obj;
}
}
class Main {
public static void main(String[] args) {
// Test for Integer type
Test < Integer > obj1 = new Test < Integer > (5);
System.out.println(obj1.getObject());
// Test for double type
Test < Double > obj2 = new Test < Double > (15.777755);
System.out.println(obj2.getObject());
// Test for String type
Test < String > obj3 = new Test < String > ("Yayy! That's my first Generic Class.");
System.out.println(obj3.getObject());
}
}As you can see we create 3 different Integer, Double, and Stringtypes variables for three different generic class objects.
Generic For loop
Java Generic has a new loop called for-each loop.
Get Nathan Chiche’s stories in your inbox
Join Medium for free to get updates from this writer.
It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes.
In normal for loop:
for( ObjectType variable : iterable/array/collections ){
// code using name variable
}It is similar to this
for( ObjectType variable : iterable/array/collections ){
// code using name variable
}This is how you would use it:
import java.util.*;
public class practice2{
public static void main(String[] args){
Integer[] nums = {1, 2, 3, 4};
Character[] letters = {'a', 'b', 'c', 'd'};
printMe(nums);
printMe(letters);
}
//Generic method
public static <T> void printMe(T[] i){//parameter of t array
// generic for loop where x stores the int, and char
// value stored at every index of array
for(T x : i){
System.out.printf("%s ", x);
}
//space after every printMe
System.out.println();
}
}Generic return Type:
We can use generics to extend to different classes and interfaces using:
//class from java.lang.Number
Public class List<T extends Number>{}
//interface from java.lang
Public class List<T extends Comparable>{}Let's take a problem as an example we can’t use the greater than or less than signs to compare all different types of data like strings, ints etc
We need a method to use for any sort of data:
public static <T extends Comparable<T>> T max(T a,T b, T c){}Break it down:
<T extends Comparable<T>>
This means only objects that inherit from comparable class can be used in this method.
T max(T a,T b, T c){}
For return type instead of putting something like void number string. You just put T after < > which means your returning generic data or type of data
Full Program
import java.util.*;
public class practice3{
public static void main(String[] args){
//returns max number
System.out.println(max(23,81,67));
//returns letter max letter
System.out.println(max("apples", "chicken", "tots"));
}
public static <T extends Comparable<T>> T max(T a,T b, T c){
T max = a;
if(b.compareTo(a)> 0){
max = b;
}
if(c.compareTo(max) > 0){
max = c;
}
return max;
}
}









