0

I couldn't find an answer to this exact question anywhere else, but I apologize if it's a duplicate.

I usually see generic initialization done like this, with the type parameter next to the reference type, as well as the object declaration:

Box<Integer> integerBox = new Box<Integer>();

Or, in the "short-hand" method (since Java 7), using the diamond:

Box<Integer> integerBox = new Box<>();

However, I noticed that the code still works after omitting the parameter type next to the object declaration like so:

Box<Integer> integerBox = new Box();

How come? Is this some compiler magic (I'm using NetBeans, by the way).

Thanks in advance.

Polymorph
  • 23
  • 5
  • You can find a great answer to this general question here. http://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7 – Sam5487 Jun 07 '15 at 03:36

2 Answers2

1

This one:

Box<Integer> integerBox = new Box();

assigns a raw Box to integerBox, bypassing generic type checks. While that might look fine in this case, it isn't so great when you have something like

List<String> strings = Arrays.asList("a", "b", "c");
...
List<Integer> integers = new ArrayList(strings);

If you do

List<Integer> integers = new ArrayList<>(strings);

then the compiler will detect the type mismatch.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

If you compile that, you'll get a warning: unchecked conversion. This means that, when you initialize integerBox to a raw type, even though it was declared as a generic type, the compiler will still bypass generic type checking.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48