Search code examples
javagenericslanguage-design

Why do we need to provide generic information twice?


Another very basic question regarding generics in Java and follows directly from a previous question of mine . Aren't we providing the same information to the compiler two times by writing the code below . Why do we need to provide the both in the left hand side as well as on the right hand side ?

List<Number> numbers = new ArrayList<Number>();

Edit: As I see in some answers that it it not required any more in java 7 onwards. But I would like to know what was the reason that it wasn't possible before java 7 ?


Solution

  • Because pre java 7 does not support generic type inference for constructors. This is solved in java 7 by the diamond operator.
    You could also write generic factory methods as a workaround like:

     public static <T> List<T> createArrayList() {
          return new ArrayList<T>();
     }
    

    then

    List<Integer> list = createArrayList();
    

    Which is questionable but works. And maybe pays off well for Maps and other multi-argumented generic types.


    To the edit: maybe the language designers decided to not support generic type inference because they implemented generics with type erasure. An other questionable decision, I think... Otherwise don't think that there is any serious reason against this feature in earlier java versions. (And by Peter Lawrey's addendum, it is still not present.)