Java Generics is a simple and great feature of the java technology. I have been asked about it in many job interviews and professional gatherings. In fact, I also ask about Java Generics when chatting with a java newbie or a professional and guess what ? Even the professionals sometimes don’t know what exactly java generics is; though they have used it extensively in their projects.
So, let’s get started with
A Brief Introduction
Java Generics was introduced in Java Standard Edition (SE) 5.0. As shown by its name, it generalizes your code. Now, by generalization, we mean general or generic code which is independent of a particular type.
Not getting much ? Well, to have a better understanding, let us get a look at
Motivation behind Generics
1 – Elimination of casting
Back in the old days, before generics, when you added something to a java list, like
List list = new ArrayList(); list.add("hello");
and you wanted a value from it
String s = (String) list.get(0);
you were required to cast it because the compiler didn’t know the type of the object that was returned from the list.
Generics, is our guy. It eliminated the need for casting. Using generics, we can do it like
List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // see, no need of casting, voila :)
No more need to explicit type casting. Generics takes care of that.
2 – Stronger type checks at compile time
If you have ever developed something, you would agree that compile time errors are always easier to eradicate as compared to runtime errors or exceptions. Generics, made it easier for the compiler to detect any compile time errors, which helps us, the developers.
For example, see the above example, if you try to add any other value to the list than a string, like
List<String> list = new ArrayList<String>(); list.add(1);
the compiler would give an error, hence, saving you from a hectic bug on runtime which if you ask me, really annoys me.
3 – Enabling programmers to implement generic algorithms
As discussed in the Introduction part, generics enable programmers to implement generic algorithms which can be:
- Generic class declarations
- Generic interface declarations
- Generic method declarations
- Generic constructor declarations
Let’s try to understand Generic class declarations first.
Say we have a class
public class Car { private Object object; public void set(Object object) { this.object = object; } // setter public Object get() { return object; } // getter }
Now using generics, the code would be
/** * Generic version of the Car class. * @param <T> the type of the value being used */ public class Car<T> { // T stands for "Type" private T capacity; public void set(T capacity) { this.capacity = capacity; } public T get() { return capacity; } }
This generalizes the class by using the type and it can now be used for any type including primitives like int, string etc.
Now if we try
Car<Double> myCar = new Car<Double>(); myCar.set(new Integer(1)); // compiler error
This would cause a compiler error because the types mismatch.
Interface declarations are the same as class declarations.
Now, to understand constructor declaration, add a constructor to the Car class
/** * Generic version of the Car class. * @param <T> the type of the value being used */ public class Car<T> { // T stands for "Type" private T capacity; public Car(T capacity){ // constructor declaration this.capacity = capacity; } public void set(T capacity) { this.capacity = capacity; } public T get() { return capacity; } }
Method declaration is the most important part of java generics. It is used very extensively to achieve higher efficiency with lesser amount of code.
To understand method declaration, lets look at an example.
Say, we want to write a method to find maximum value between two variables
public T max(T obj1, T obj2) { if (obj1.compareTo(obj2) > 0) { return obj1; } return obj2; } System.out.println(max(new Integer(1), new Integer(2)));
Similarly we can also use
System.out.println(max(new Double(1.3), new Double(2.6)));
Summary
We discussed the Java Generics. The motivation behind java generics. Cast elimination, compiler checks, generic algorithms and its types. I have tried to keep it as simple as possible. However, Generics is a very broad topic, though I didn’t discuss each and every detail of java generics but I tried to summarize it so that you can have a general idea of what it is.
If you like this article, you can do me a favour by sharing it on social media.
Thanks 🙂
References
(official java jenerics docs)
http://docs.oracle.com/javase/tutorial/java/generics/
(other articles)
http://www.javacodegeeks.com/2011/04/java-generics-quick-tutorial.html
http://www.codeproject.com/Articles/27611/Generics-in-Java-Part-I
very informative post….
Pingback: Java Versions, Features and History | Mudassir Shahzad