28

I'm working with a 3d party library, and they return Collections that lack type specifications (e.g. public List getFoo();) , and I'm trying to convert their return types and return a list with a proper type.

I have created a simple example that demonstrates the problem. e.g.

edit The original question declared l2 as an ArrayList rather than a List, that is corrected now.

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Foo {
    public static void main(String[] args) {
        ArrayList l = new ArrayList();
        l.add(1);
        l.add(2);
        List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());
    }
}

This fails to compile.

$ javac Foo.java
Foo.java:10: error: incompatible types: Object cannot be converted to List<String>
        List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());
                                                                  ^
1 error

If I modify the program slightly so it compiles and I can check the return type of the stream/collect operation. It "works", although I'd have to cast the result.

e.g.

import java.util.ArrayList;
import java.util.stream.Collectors;

public class Foo {
    public static void main(String[] args) {
        ArrayList l = new ArrayList();
        l.add(1);
        l.add(2);
        Object l2 = l.stream().map(Object::toString).collect(Collectors.toList());
        System.out.println(l2.getClass());
    }
}

Running this shows...

$ javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ java Foo
class java.util.ArrayList

As expected.

So, Collectors.listCollector() does the right thing at runtime, but is this compile time behavior expected? If so, is there a "proper" way around it?

9
  • 1
    Do you know yourself the actual type the list is going to have? Does the library ensures that the list returned is a List<Something> but is returning for some reason List?
    – Tunaki
    May 13, 2016 at 16:11
  • 1
    You should tell the maintainer of the 3rd party library to get with the program. Java's generics were introduced 12 years ago. But I'm sure there's a long and sad tale that explains this.... :-) May 14, 2016 at 1:41
  • 2
    @Bill One big problem here is that you're using raw types. If you don't know what the ArrayList is a list of, use ArrayList<?>, not raw ArrayList. The use of raw types is, in turn, making it harder for the compiler to give you the error message that would have made you say "doh, I get it" -- toList() returns a List, not an ArrayList. (Also, the problem you had here has nothing whatsoever to do with streams, other than you happened to have used streams -- this is just not understanding the Java type system sufficiently.) May 15, 2016 at 1:36
  • 2
    @Bill That's what happens when you pass raw types into a generic library -- things collapse to Object. Raw types exist solely to ease migration from pre-generic (1.4) to generic code. That transition was 12 years ago. May 15, 2016 at 15:26
  • 1
    @BrianGoetz The transition to generics started 12 years ago, but it apparently continues to this day.... :-/ May 15, 2016 at 16:19

2 Answers 2

36

The stream(), map(), collect(), and all the other stream methods rely on generic typing for things to work well. If you use a raw type as input, then all the generics are erased, and everything turns into a raw type. For example, if you have a List<String>, calling the stream() method gives you an object of type Stream<String>.

But if you start out with a raw type List, then calling stream() gives you an object of the raw type Stream instead.

The map() method has this declaration:

    <R> Stream<R> map(Function<? super T,? extends R> mapper)

but since it's called on a raw Stream, it's as if the declaration is

    Stream map(Function mapper)

so the result of calling map() is simply a Stream. The signature of collect() is filled with generics:

    <R> R collect(Supplier<R> supplier,
                  BiConsumer<R,? super T> accumulator,
                  BiConsumer<R,R> combiner)

When called with a raw type, it gets erased to

    Object collect(Supplier supplier,
                   BiConsumer accumulator,
                   BiConsumer combiner)

so the return type of your stream pipeline is Object when its source is a raw type. Obviously this isn't compatible with ArrayList<String> and you get a compilation error.

To fix this, bring your types into the generic world as soon as possible. This will probably involve unchecked casts, and you should probably suppress the warning. Of course, do this only if you're sure the returned collection contains objects only of the expected type.

In addition, as Hank D pointed out, the toList() collector returns a List, not an ArrayList. You can either assign the return value to a variable of type List, or you can use toCollection() to create an instance of ArrayList explicitly.

Here's the code with these modifications included:

    @SuppressWarnings("unchecked")
    ArrayList<Integer> l = (ArrayList<Integer>)getRawArrayList();
    l.add(1);
    l.add(2);
    ArrayList<String> l2 = l.stream()
                            .map(Object::toString)
                            .collect(Collectors.toCollection(ArrayList::new));
0
5

Collectors.toList() returns a List, not an ArrayList. This will compile:

public static void main(String[] args) {
    ArrayList<?> l = getRawArrayList();
    List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());

}
4
  • The library I'm using returns the undecorated type. So, unless I cast it, that decision is out of my hands. May 13, 2016 at 17:05
  • 1
    @Bill, I updated the answer to assume a function that returns a raw ArrayList. ArrayList<?> will accept an ArrayList without a cast.
    – Hank D
    May 13, 2016 at 18:03
  • 1
    Thanks, apparently, the compiler treats ArrayList and ArrayList<?> differently. I ended up casting the list to List<expectedtype> and it worked. I'm mostly curious about why it can't figure out that it's a list and decays into an Object. Not sure about what it is that I don't understand about the situation, and I'd like to fill that knowledge gap. May 13, 2016 at 21:10
  • Thanks for noticing that, after a couple of days distance from the question, I realized that mistake in the initial example. I have fixed it. May 15, 2016 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.