Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the difference in declaration of generic Lists?

I want to decare two Lists: First is a list of Integers. I decare it as:

  List<Integer> ints= Arrays.asList(1,2,3);

It works fine.

Second is a list of Objects. I declare it as:

  List<Object> objs= Arrays.asList(1,2.13,"three");

But it gives a error in eclipse as soon as I write it. The error is:

  Multiple markers at this line
- Type mismatch: cannot convert from List<Object&Comparable<?>&Serializable> to 
 List<Object>
- Type safety: A generic array of Object&Comparable<?>&Serializable is created for
       a varargs parameter

Instead if I write

  List<Object> objs = Arrays.<Object>asList(1,2.13,"three");

It works fine.

I am not able figure out the reason.

like image 857
Dipesh Gupta Avatar asked Mar 30 '12 11:03

Dipesh Gupta


People also ask

Why do we use generics for getting a list of multiple elements?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

What is generic declaration?

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas.


1 Answers

Look at this post on stackoverflow.

15.12.2.7 Inferring Type Arguments Based on Actual Arguments

A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection

The most restrictive type intersection between String,Double and Integer is both the interfaces Comparable and Serializable. So when you write

Arrays.asList(1,2.13,"three"); 

It infers T to be implements Comparable<?>, Serializable.Then it is as if you are doing

List<Object> objs = new List<T extends Comparable<?>, Serializable>

Obviously, this is not allowed.
On the other hand, when you specify Object explicitly using

Arrays.<Object>asList(1,2.13,"three");

no inference is made

like image 171
UmNyobe Avatar answered Sep 28 '22 03:09

UmNyobe