Java Generics in layman language

Why Generics, what were the issues?

List integers = new ArrayList();
integers.add(1);
integers.add(2);
integers.add("three");
for(int i=0;i<list.size();i++) {
if(list.get(i) == (Integer)list.get(i)) {
System.out.println(2*(Integer)list.get(i));
} else {
System.out.println(1);
throw new IllegalArgumentException("Value is not integer");
}
}
public static void main(String[] args) {
Set data = new HashSet();
Set updatedData = getData(data);
}
public static Set getData(Set data) {
data.add(1);
data.add("Two");
data.add(new ArrayList<>());
return data;
}
List<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add("three"); // compile time exception

Type Erasure

List<Integer> list1 = new ArrayList<>();List list2 = new ArrayList<>();

Generic class

public class GenericClass<T,E> {
private T key;
private E value;
}
GenericClass<Integer,Integer> integers = new GenericClass<>();
GenericClass<String,Integer> strings = new GenericClass<>();

Generic Interface

public interface GenericInterface<T,E> {
T firstMethod();
E secondMethod();
}
public class SampleClass implements GenericInterface<Integer,String> {
@Override
public Integer firstMethod() {
return null;
}
@Override
public String secondMethod() {
return null;
}
}

Generic methods

public <T,E> void genericMethod(T key,E value) {
System.out.println(key);
System.out.println(value);
}
public static <T> Map<T,T> staticGenericMethod(T val1,T val2) {
Map<T,T> map = new HashMap<>();
map.put(val1,val2);
return map;
}
public <T> Map<T,T> staticGenericMethod(T val1,T val2) {
Map<T,T> map = new HashMap<>();
map.put(val1,val2);
return map;
}

Generic Constructor

public class ClassWithGenericConstructor<T> {
private T key;
private T value;
public ClassWithGenericConstructor(T key,T value) {
this.key = key;
this.value = value;
}
}
public class ClassWithGenericConstructor {
public <T> ClassWithGenericConstructor(T key,T value) {
System.out.println(key);
}
}

Generics in Array :

public class GenericArray<T> {
// this one is fine
public T[] notYetInstantiatedArray;
// causes compiler error; Cannot create a generic array of T
public T[] array = new T[5];
}

WildCards

Collection<?> coll = new ArrayList<String>();
List<? extends Number> list = new ArrayList<Long>();
Pair<String,?> pair = new Pair<String,Integer>();

Unbounded

Collection<?> coll = new ArrayList<String>();

Bounded

List<? extends Number> list = new ArrayList<Long>();
List<? super Integer> list = new ArrayList<Number>();

Limitations of Generics

  1. Static fields of parameterized type are not allowed
private static T member; //This is not allowed
  1. We cannot create an instance of type parameter directly
new  T();   // not allowed
  1. Not compatible with primitive types
List<int> ids = new ArrayList<>();    //Not allowed
  1. Generic Exception class is not allowed
public class GenericException<T> extends Exception {}

--

--

--

Full stack developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introduction to Tilemaps!

Fundamental programming patterns I — Loops

Functional Programming in PicoLisp

A Comprehensive Guide to Installing Apache Web Server on CentOS 7

How to Configure Allure report for Rest Assured API automation scripts.

Arduino Activated ‘Smart’ (Mechanical) Lock

How to deploy a single Kubernetes cluster across multiple clouds using k3s and WireGuard

Importance of PyTorch To Develop Deep Learning Models

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rohan Aggarwal

Rohan Aggarwal

Full stack developer

More from Medium

JAVA Volatile Variables

Spring explained: What is Spring? And what is Spring Boot?

Using DevTools in IntelliJ

Collections in Java • Garbage Collector