Generics are a function of Java that allows programmers to specify the type of data they want to work with in a class, interface, or method. In this tutorial, let’s learn more about generics in Java.
Why need generics?
Before generics is introduced, we only work with classes, interfaces or methods with a fixed data type.
For example, we declare a List object as follows:
1 |
List l = new ArrayList(2); |
With the above declaration, assume that we want to work only with the String object. But because l variable is a Collection of Object objects, so we can use it with any type of data. The following declaration will be valid:
1 2 |
l.add("Khanh"); l.add(new Integer(1)); |
This will entangle the type of data we want to work on, and sometimes we do not have control over the compile time.
That is the reason for the need for generics in Java. With generics, we will specify the type of data we will work on at compile time.
The above example can be rewritten as follows:
1 |
List<String> l = new ArrayList<String>(2); |
Then, the following statement will report the error immediately:
1 |
l.add(new Integer(1)); |
How to create a class generics in Java
First, let’s define a non-generics class first and then convert this class to the generics class.
The content of the non-generics class is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava; class Student { private Object obj; public void set(Object obj) { this.obj = obj; } public Object get() { return obj; } } |
With this definition, the obj attribute of the Student object and the obj parameter in the set() method could be any object. And if the two objects are different, an exception will occur.
To fix the data type for the obj attribute, and in the set() method, we will apply generics in Java. As follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava; class Student<T> { private T obj; public void set(T obj) { this.obj = obj; } public T get() { return obj; } } |
Uses generics class
To use generics class, when initializing an object, we will pass the type of data we want to that object.
For the Student example above, we can initialize the Student object with the String data type as follows:
1 |
Student<String> student = new Student<String>(); |
At this point, we cannot use the set() method with other String data types, for example: