Search code examples
javajava-7type-inferencediamond-operator

Why diamond operator is used for Type Inference in Java 7?


List<String> list = new ArrayList(); will result in compiler warning.

However the following example compiles without any warning: List<String> list = new ArrayList<>();

I'm curious why introducing of diamond operator is needed at all. Why not just have type inference on constructor if type argument is absent (as its already done for static methods in java and exploited by collection libraries like google guava)

EDIT: Using millimoose answer as starting point I looked what type erasure actually is and it's not just removing all type information. Compiler actually does a bit more(copied from official doc):

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

Solution

  • The definitive answer would have to come from someone who designed that feature, but I'm assuming it's to distinguish this from using raw types, which make the compiler do something different altogether for the sake of compatibility. An expression with a raw type in it is processed subtly differently than one that involves generics, an example is found in this SO question: Generic screws up non-related collection