1

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?

4
  • Do you compilation error for "List<Object> objs = Arrays.asList(1,"2");"? I just tried it and I didn't get any compilation error. Commented Jan 4, 2016 at 10:29
  • It works for Java 8 :) Commented Jan 4, 2016 at 10:29
  • <? extends Object> List<? extends Object> java.util.Arrays.asList(? extends Object... arg0) Commented Jan 4, 2016 at 10:31
  • What Java version are you using? Type inference is slowly getting better and your example compiles fine with Java8. Commented Jan 4, 2016 at 10:34

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.