Created: 2023-09-07 17:14
Status: #concept
Subject: Programming
Tags: Java Java Data Type TypeScript Generics ArrayList java.util.HashMap java.util.Comparable
Java Generic
Generics allow our classes to be used with multiple data types.
- we declare them after the class name, like how they are used.
class Name<T1, T2> { ... }
/**
* Generic version of the Box class.
* @param <T> the type of the value being stored in a box.
*/
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
- You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument —
Integer
in this case — to theBox
class itself.
Box<Integer> integerBox = new Box<>(); // evaluates to Integer with Type Inference
integerBox.set(5);
System.out.println(integerBox.get());
Generic Interfaces
We don't have to write the type parameter directly after the
class Name
when we implements SomeInterface<T>
as we use <T>
as the type generic.
- this allows our implementing class to implicitly bind themself to a type.
public interface List<T> {
void add(T value);
T get(int index);
T remove(int index);
}
public class MovieList implements List<Movie> {
// object variables
@Override
public void add(Movie value) {
// implementation
}
@Override
public Movie get(int index) {
// implementation
}
@Override
public Movie remove(int index) {
// implementation
}
}
Interface & Class with Generics
On the other hand, if we add a generic to a
class Name<T>
, we are implementing a generic class that is more flexible.
public class GeneralList<T> implements List<T> {
// object variables
@Override
public void add(T value) {
// implementation
}
@Override
public T get(int index) {
// implementation
}
@Override
public T remove(int index) {
// implementation
}
}
Naming Convention
The most commonly used type parameter names are:
E
- Element (used extensively by the java.util.Collection Framework)K
- KeyN
- NumberT
- TypeV
- ValueS
,U
,V
etc. - 2nd, 3rd, 4th types