1

So I've noticed that doing something like:

LinkedList list = new LinkedList();

Gives you a warning from the compiler, so I was always taught that the correct way was:

LinkedList<Integer> list = new LinkedList<Integer>();

But I've noticed that doing

LinkedList<Integer> list = new LinkedList<>();

Doesn't throw a warning either, although I don't quite understand why. Could someone explain to me the difference between these last two examples, and if one is preferable to another, either style wise or just practically?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Brandon
  • 1,029
  • 3
  • 11
  • 21
  • 1
    possible duplicate [What is the point of the diamond operator in Java 7?](http://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7) – Reimeus Dec 25 '13 at 20:36
  • how about this : List list = new LinkedList(); – Ashish Dec 25 '13 at 20:38
  • Technically, there's zero point in specifying a type for a constructor, since the type has no effect on what actually gets constructed, and no actual values are added to the object. – Hot Licks Dec 25 '13 at 20:41

3 Answers3

3

The Diamond

In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box<Integer> with the following statement:

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

For more information on diamond notation and type inference, see Type Inference.

Read more here and here

Radiodef
  • 37,180
  • 14
  • 90
  • 125
nachokk
  • 14,363
  • 4
  • 24
  • 53
2

Both

LinkedList<Integer> list = new LinkedList<Integer>();

and

LinkedList<Integer> list = new LinkedList<>();

are equivalent. When you use the 'diamond' (<>) the compiler uses type inference to work out what type you mean. So in this case, since it's being assigned to a variable of type LinkedList<Integer>, it assumes this is what you want to create (which you do).

Meindratheal
  • 158
  • 2
  • 6
1

The reason that you are having unchecked warning in the first case is that you are declaring the Collection LinkedList as Raw type. The term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety for future operation.

The diamond operator, however, allows the right hand side of the assignment to be defined as the same type parameters as the left side using the mechanism of Type inference allowing us safety of generics with almost the same effort with defining the type in the right side: which is indeed unnecessary.

Sage
  • 15,290
  • 3
  • 33
  • 38