I'm using Java 8's Stream
functionality to manipulate the contents of an array in my program:
Obstacle[] closestObstacles = Stream.generate(() -> new Obstacle()).limit(8).toArray(Obstacle[]::new); // one for each line of attack
When I try importing Stream
like this: import java.util.*;
I get a "the symbol Stream cannot be resolved" error. When I instead import Stream
like this: java.util.stream;
things work as expected. Why does this happen? I don't use Stream
or anything named "stream" elsewhere in my program, so I don't think it's a name conflict?
I doubt that the second attempt (import java.util.stream;
) works. As JonSkeet pointed out in their comment, it should result in a compilation error: error: cannot find symbol
. Maybe you wanted to import java.util.stream.*;
?
To the actual question:
If we import with a wildcard, that is the asterisk (*
) character, only the direct classes in this package will be imported, not the classes in sub-packages. Thus with an import java.util.*
, we import classes like ArrayList
, LinkedList
and Random
. A full list can be found here. The class Stream
actually resides in the sub-package java.util.stream
and is not imported when you import java.util.*;
.
To import Stream
, we can either import java.util.stream.*;
(all classes within this package) or only import java.util.stream.Stream;
(the FQCN of the class we need).