user3650602
user3650602

Reputation: 175

Creating a List of Objects throwing compiler error

I am currently studying generics as part of my programming class, and I'm having problems understanding why the following code throws a compiler error:

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

From what I'm aware, if you do not explicitly declare the type parameter for the method, for example Arrays.<Integer>asList(); then it is generated for you, using the most reasonable choice.

The following code:

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

works because i'm explicitly telling the compiler, "I want this method's type parameter to be Object", but I am curious why this is not done successfully automatically?

Upvotes: 1

Views: 150

Answers (2)

Fred Porci&#250;ncula
Fred Porci&#250;ncula

Reputation: 8902

List<Object> objs = Arrays.asList(1, "2") will only work with Java 8 :)

Even List<Object> objs = Arrays.asList("a", "b") will compile with Java 8.

Check these references:

Upvotes: 2

ameishutovich
ameishutovich

Reputation: 189

This issue appears because different type arguments were passed to a method Arrays.asList, so the compiler tried to find the intersection of all super types of your type arguments.

You created a list with String and int parameters. So compiler found only Serializable as common interface.

This will be compiled:

List<? extends Serializable> list = Arrays.asList(1, "2");

Reference to read: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ404

Upvotes: 2

Related Questions