2

When I execute the below code it works without any problem.

List<String> singletonList = Collections.singletonList("Hello");
List<String> s = Collections.emptyList();
singletonList.addAll(s);

However, when I try to do following it gives me compile error. Why?

List<String> singletonList = Collections.singletonList("Hello");
singletonList.addAll(List<String> Collections.emptyList());

Collections.emptyList is a type-safe way of creating an empty list. But why doesn't my program compile then? I know I cannot add to immutable list (UnsupportedOperationException) but adding an empty list is allowed. Actually I was testing this and I noticed above thing.

2
  • after reading the answers, i'm curious to know what java version you are using. Commented Apr 17, 2014 at 19:07
  • When you get a compile error and you ask a question about it, always include the exact error message in your question - that makes it a lot easier to help you. Commented Apr 17, 2014 at 19:29

2 Answers 2

4

Collections.emptyList() returns List<Object> which isn't (does not have any type relationship with) List<String> so casting is not allowed.

What you need is following:

singletonList.addAll(Collections.<String>emptyList());
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. Your code works. But why casting is not allowed? I can write Object o = "abc";
@ParagJ A String is an Object, but a List<String> is not a List<Object>
There has to be a type relationship (parent-child, child-parent) for the casting to work. e.g. String is an Object.
And why this works then ? List<String> s = Collections.emptyList();
That's when @SotiriosDelimanolis' answer comes into picture. There is some thing called automatic type inference, where compiler tries to infer the return type based on the context. In version 7 it works in the declaration, but as you can see in his answer, in version 8, in works in method call also.
|
2

In Java 8, the type inference is improved. You can do

List<String> singletonList = Collections.singletonList("Hello");
singletonList.addAll(Collections.emptyList());

The type argument for the invocation of emptyList() will be inferred from the context it is used in, ie. it expects a Collection<? extends String>.

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.