我知道导入 *
是一种不好的做法,最好明确导入我们真正需要的内容。但是,我很好奇为什么导入 util.*
不包含 util.stream.*
。
如果我import java.util.stream.*;
这段代码运行成功:
int[] a = {3, 4, 1};
ArrayList<Integer> list = Arrays.stream(a)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
但是,如果我从 stream
中删除 import
:
import java.util.*;
失败:
Main.java:20: error: cannot find symbol
.collect(Collectors.toCollection(ArrayList::new));
^
symbol: variable Collectors
location: class Ideone
1 error
我已经尝试过 Java 8 (1.8.0_201):
https://www.onlinegdb.com/online_java_compiler
Java 11 (11.0.11+9-Ubuntu-0ubuntu2.20.04):
https://www.programiz.com/java-programming/online-compiler/
和 Java 12 (12.0.1+12):
答案 0 :(得分:2)
您正在使用 wildcard import
导入包 not the sub-packages inside it
中的所有类。
import java.util.*;
上面的import语句将导入java.util包内的所有Classes 而不是子包即java.util.stream
,所以为了导入它,你需要像
import java.util.*;
import java.util.stream.*;
答案 1 :(得分:0)