How to use Generics In Java
Generics in Java are a way to create classes, interfaces, and methods that work with different types of data.
Published in
2 min readJan 26, 2023
They allow you to write reusable code that can work with any data type, rather than being limited to a specific type. Here is a simple example of a generic class in Java:
public class GenericExample<T> {
private T value;
public GenericExample(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
In this example, the class GenericExample
is defined with a type parameter T
. This means that when an instance of the class is created, the type of value
must be specified. For example:
GenericExample<Integer> example1 = new GenericExample<Integer>(5);
Integer value = example1.getValue();
GenericExample<String> example2 = new GenericExample<String>("Hello");
String value2 = example2.getValue();
You can also use generics with interfaces and methods in Java. Here is an example of a generic interface:
interface GenericInterface<T> {
T getValue();
void setValue(T value);
}