Question

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 ?

Was it helpful?

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.)

OTHER TIPS

There is the diamond operator being introduced which removes this redundant information.

See this SO link as well What is the point of the diamond operator in Java 7?

From my reading / understanding I dont think generics were done that well in java. The ? operator introduced at the end is a pain to work with. The fact there is erasure shows that it was shoe-horned in in my opinion. It does the job but I think it could be so much better

Because one is the reference and one is the implementation. The left hand of the line is setting up the reference that you store the instantiated variable in. As Java uses "run-time type erasure" to implement Generics, there is no way for any code beyond the reference assignment to know what Generic parameter was assigned.

Edit - I did not know about the change in J7 (I'm a bit out of date :) ) - looks like they solved this issue.

As well as the reasons described in the other answers, the argument on the right side in this example does not need to be exactly the same as the left one. Example:

List<? extends Calendar> cals = new ArrayList<GregorianCalendar>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top