为什么导入 java.util.* 不足以导入流?

时间:2021-07-19 03:49:48

标签: java import java-8 java-stream

简短版本:

我知道导入 * 是一种不好的做法,最好明确导入我们真正需要的内容。但是,我很好奇为什么导入 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):

https://ideone.com/7XfIFY

2 个答案:

答案 0 :(得分:2)

您正在使用 wildcard import 导入包 not the sub-packages inside it 中的所有类。

import java.util.*;

上面的import语句将导入java.util包内的所有Classes 而不是子包即java.util.stream ,所以为了导入它,你需要像

这样的import语句
import java.util.*;
import java.util.stream.*;

Read more on Importing packages

答案 1 :(得分:0)

虽然包名看起来更像是一种层次关系的体现,但其实不然。

包名最像是类的前缀。

具体说明请参考official document(Apparent Hierarchies of Packages)