Java Generics

Java Genrics was introduced in Java 5.

Java Generics provide compile-time type checking and remove risk of ClassCastException

// Compile Time type checking provided by generics
List list1 = new ArrayList(); // In java 7 we can intialize with List list1 = new ArrayList<>(); 
list1.add("abc");
//list1.add(new Integer(5)); //throws compiler error

 

Java Generic Classes, Interfaces & Methods:

Java Generic Classes

public class GenericsType<T> {
	private T t;	
	public T get(){
		return this.t;
	}	
	public void set(T t1){
		this.t=t1;
	}	
	public static void main(String args[]){
		GenericsType<String> type = new GenericsType<>();
		type.set("Pankaj"); //valid
		
		GenericsType type1 = new GenericsType(); //raw type
		type1.set("Pankaj"); //valid
		type1.set(10); //valid and autoboxing support
	}
}

If we don’t provide the type at the time of creation, compiler will produce a warning that “GenericsType is a raw type. If we don’t provide type, the type becomes Object and hence it’s allowing both String and Integer objects but we should always try to avoid this because we will have to use type casting while working on raw type that can produce runtime errors.

 

Java Generic Interface

public interface Comparable<T> {
public int compareTo(T o);
}

 

Java Generic Method

//Java Generic Method
public static <T> boolean isEqual(GenericsType<T> g1, GenericsType<T> g2){
	return g1.get().equals(g2.get());
}

We can call the above method:
boolean isEqual = GenericsMethods.<String>isEqual(g1, g2);
boolean isEqual = GenericsMethods.isEqual(g1, g2); // Type Inference

 

Invoking a generic method as an ordinary method, without specifying a type between angle brackets is known as Type Inference. Compiler will infer the type that is needed.

 

Java Generics & Inheritance

MyClass<String> myClass1 = new MyClass<String>();
MyClass<Object> myClass2 = new MyClass<Object>();
//myClass2=myClass1; // Compilation Error since MyClass<String> is not a MyClass<Object>

Object obj = new Object();
obj = myClass1; // Valid MyClass<T> parent is Object

This is Valid
ArrayList<E> implements List<E> that extends Collection<E>, so ArrayList<String> is a subtype of List<String> and List<String> is subtype of Collection<String>.

interface MyList<E,T> extends List{
}

 

Java Generics Wildcards

Question mark (?) is the wildcard in generics and represent an unknown type. The wildcard can be used as the type of a parameter, field, or local variable and sometimes as a return type.

 

Java Generics Upper Bounded Wildcard: We use generics wildcard with extends keyword

public static double sum(List<? extends Number> list){
	double sum = 0;
	for(Number n : list){
		sum += n.doubleValue();
	}
	return sum;
}

Invocation:
List<Integer> ints = new ArrayList<>();
ints.add(3); ints.add(5); ints.add(10);
double sum = sum(ints);

Can be used as List doubless= new ArrayList<>();

 

Java Generics Unbounded Wildcard

public static void printData(List<?> list){
	for(Object obj : list){
		System.out.print(obj + "::");
	}
}

 

Java Generics Lower Bounded Wildcard : We use generics wildcard (?) with super keyword and lower bound class to achieve this.

public static void addIntegers(List<? super Integer> list){
	list.add(new Integer(50));
}

 

Java Generics Type Erasure

Generics in Java was added to provide type-checking at compile time and it has no use at run time, so java compiler uses type erasure feature to remove all the generics type checking code in byte code and insert type-casting if necessary. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

 

Java Generics Concept:

1)
List<Number> numbers = new ArrayList<Integer>(); // Invalid can cause ClassCastException

2)
We can’t create generic array? or write code as 
List<Integer>[] array = new ArrayList<Integer>[10]; // Invalid
because Java Generics Type Erasure


 

Links to refer to: Post 1 , Post 2;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s