Alex Rivera | Logout

What is the difference between these statements in a generic class?

Asked 2013-02-22T11:41:35.720
10

I am still learning about generics and have a question. Say you had this generic class:

public class Test<T> {

    public static void main (String[] args) {
        Test t1 = new Test();
        Test<String> t2 = new Test<String>();
        Test t3 = new Test<String>();
    }
}

All the statements compile but I don't really know what makes them different. Can anyone give me a brief explanation on those three statements.

Edit
Report

1 Answer

2

They all actually create identical objects. The only difference will be how they are treated syntactically in the rest of the code.

t1 and t3 will be treated in exactly the same way because they are the same type - they will be treated as an object with class Test, nothing more.

t2 will be treated more rigorously in terms of type checking. If some opportunity presents itself for the compiler to make use of its generic <String> quality then that quality will also be required to match.

answered 2013-02-22T11:53:08.800

Your Answer