Java-Generic with Multiple Parameters

Generic with Multiple Parameters

You can declare more than one type parameter in a generic type. To specify two or more type parameters, simply use a comma-separated list. For example, in the following program, GenClass specifies two type parameters : T and V, separated by comma. Because it has two type parameters, two type arguments must be passed to GenClass when an object is created, as :

Generic with Multiple Parameters

In this case, Integer is substituted for T, and String is substituted for V. It is possible for both types to be the same. For example, the following line of code is valid :

Generic with Multiple Parameters

In this case, both T and V would be of type String. Of course, if the type arguments were always the same, then two type parameters would be unnecessary.


Generic with Multiple Parameters Generic with Multiple Parameters

Program Source

class GenClass<T, V> {

    T tob;
    V vob;

    GenClass(T to, V vo) {
        tob = to;
        vob = vo;

    T getFirstObj() {
        return tob;

    V getSecondObj() {
        return vob;

    void showTypes() {
        System.out.println("T Type : " + tob.getClass().getName());
        System.out.println("V Type : " + vob.getClass().getName());

public class Javaapp {

    public static void main(String[] args) {

        GenClass<Integer, String> gen1 = new GenClass<Integer, String>(20, "Twenty");
        int getInt = gen1.getFirstObj();
        String getStr1 = gen1.getSecondObj();
        System.out.println("Int Value : " + getInt);
        System.out.println("Str Value : " + getStr1);
        GenClass<String, String> gen2 = new GenClass<String, String>("Twenty", "Forty");
        String getStr2 = gen2.getFirstObj();
        String getStr3 = gen2.getSecondObj();
        System.out.println("Str Value : " + getStr2);
        System.out.println("Str Value : " + getStr3);

Leave a Comment