Skip to content

Java Generic#

Java Generic#

  • Java Generics was added in Java 5 to provide compile time type checking and removing risk of ClassCastException which was common while working with collection classes.
1
2
3
    // Before Java 5

    List list = new ArrayList();
1
2
3
    // Java 5 and after

    List<String> list = new ArrayList<String>();

Generic Class#

  • We can define our own classes with generic type. A generic type is a class or interface that is parameterized over types. We use bracket (<>) to specify the type parameter.
GenericType.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package com.java.core.generic;

public class GenericType<T> {

    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}
  • Then we can create this class with setting any parameter type that we want as below:
JavaGeneric.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package com.java.core.generic;

public class JavaGeneric {

    public static void main(String[] args) {
        GenericType<String> stringGenericType = new GenericType<>();
        stringGenericType.setT("this is a string");
        System.out.println(stringGenericType.getT().getClass().getSimpleName());

        GenericType<Long> longGenericType = new GenericType<>();
        longGenericType.setT(100L);
        System.out.printf(longGenericType.getT().getClass().getSimpleName());
    }

}
  • When we run the main method, then we should see the result as below. It means, the parameter of GenericType class can be String or Long base on the type in the <> that we want when we create the GenericType class.
1
2
3
String
Long
Process finished with exit code 0

Generic Interface#

Application.java
1
2
3
4
5
6
7
package com.java.core.generic;  

public interface Application<T, S> {  

    T getApplication(S appId);  

}
  • Java Generic Type: Java Generic Type naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language.
  • The most commonly used type parameter names are:
E - Element (used extensively by Java Collection Framework. Ex: ArrayList, Set, etc)
K - Key (Used in Map)
N - Number
T - Type
V - Value (Used in Map)
S, U, V etc - 2nd, 3rdm 4th types

Generic Method#

1
2
3
4
5
6
7
8
9
public static <T> T cloneObject(T t, Class<T> type) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        String objectString = mapper.writeValueAsString(t);
        return mapper.readValue(objectString, type);
    } catch (JsonProcessingException e) {
        Throw new RuntimeException("Clone object error!: " + e.getMessage());
    }
}

See Also#