What is happening inside of this Generic<> example?

I'm studying the Generics chapter in Herbert Schildt's Java: A Beginner's Guide, 7th Edition, and I'm not exactly clear on one of the examples.

The full program:

class TwoGen<T, V> {

    T object1;
    V object 2;

    TwoGen(T obj1, V obj2) {

        object1 = obj1;
        object2 = obj2;
    }

    System.out.println("Type of T is " + object1.getClass().getName());
    System.out.println("Type of V is " + object2.getClass().getName());

    // getters

    T getObject1() {
        
        return object1;
    }

    T getObject2() {

        return object2;
    }
}

second class:

class SimpleGen{

    public static void main(String[] args) {

        TwoGen<Integer, String> twoGenObject = new TwoGen<Integer, String>(88, "Generics");

        ...snip...

    }
}

I'm struggling to understand this line:

TwoGen<Integer, String> twoGenObject = new TwoGen<Integer, String>(88, "Generics");

What exactly is happening here? To me it looks like an object of TwoGen is being instantiated, but it's being fed two arguments, so what is the result? One object that has two types? Or are two objects being constructed simultaneously here?

Or maybe I'm just misunderstanding altogether...

Posted Jul 29, 2019, 10:41 PM UTC

101
[deleted]•

It's one object containing two references to two different objects. You told the compiler your T and V fields in class TwoGen will be references to an Integer wrapper class object and a String object. object1 is now a reference to Integer containing 88, object2 is a reference to the string "Generics".

Java does things like autoboxing and String initialization under the hood allowing you to instantiate the two objects without the new keyword.

However, if you want to pass in something like an ArrayList, you would have to instantiate with new before passing it in.

7