1

I have the following code

Gen_Class<Integer> test = new Gen_Class<Integer>();

so what is the difference between <Integer> at the beginning and <Integer> at the end. and why should we write them twice ?

Is there any advantages ? and what happen if we did not add at the beginning ?

Micha agus
  • 531
  • 2
  • 5
  • 12
  • 1
    You have to specify type on both side prior to java 7, with java 7 onwards you can ignore right side type specification and just leave it as `<>` – jmj May 19 '14 at 18:23

2 Answers2

1

so what is the difference between at the beginning and at the end. and why should we write them twice ?

There's no "difference" per se; you are simply specifying the complete type name on both sides. The type is parameterized, so the type name is not complete without type arguments. However, as @JigarJoshi notes in his comment, Java 7 can infer the type arguments in many cases, allowing you to simply write the empty <> brackets on the right-hand side of an assignment, as well as for some method arguments.

Is there any advantages ? and what happen if we did not add at the beginning ?

If you leave off the type arguments on either side, you are specifying the raw type instead of the parameterized type. The consequences vary based on whether you leave the arguments off of the left side, the right side, or both.

If you leave them off the left side, then your Gen_Class<Integer> becomes a Gen_Class, which is effectively the same as a Gen_Class<Object>. This changes the semantics; places where you may have been been required to pass an Integer before may now accept any Object (which may or may not cause problems), and methods and fields which exposed Integer values may now expose Object values.

Mike Strobel
  • 25,075
  • 57
  • 69
0

If your are using Java 7 or 8, you can omit the second Integer, like this:

Gen_Class<Integer> test = new Gen_Class<>();
Danix
  • 1,947
  • 1
  • 13
  • 18