import java.util.*; 和 import java.util.* 有什么区别?并导入 java.util.stream;?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48038250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between import java.util.*; and import java.util.stream;?
提问by Adam
I'm using Java 8's Stream
functionality to manipulate the contents of an array in my program:
我正在使用 Java 8 的Stream
功能在我的程序中操作数组的内容:
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?
当我尝试Stream
像这样导入时:import java.util.*;
我收到“无法解析符号流”错误。当我Stream
像这样导入时:java.util.stream;
事情按预期工作。为什么会发生这种情况?我没有Stream
在程序的其他地方使用或任何名为“stream”的东西,所以我认为这不是名称冲突?
回答by Turing85
I doubt that your second attempt (import java.util.stream;
) works. As @JonSkeet pointed out, it should result in a compilation error: error: cannot find symbol
. Maybe you wanted to import java.util.stream.*;
?
我怀疑您的第二次尝试 ( import java.util.stream;
) 是否有效。作为@JonSkeet指出,应该导致编译错误:error: cannot find symbol
。也许你想import java.util.stream.*;
?
To your actual question:
If you 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.*
, you 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
package and is not imported when you import java.util.*;
.
对于您的实际问题:
如果您使用通配符导入,即星号 ( *
) 字符,则只会导入此包中的直接类,而不导入子包中的类。因此,使用import java.util.*
,您可以导入诸如ArrayList
,LinkedList
和 之类的类Random
。可以在此处找到完整列表。该类Stream
实际上驻留在子java.util.stream
包包中,并且在您import java.util.*;
.
To import Stream
, you can either import java.util.stream.*;
(all classes within this package) or only import java.util.stream.Stream;
(the FQDN of the class you need).
要导入Stream
,您可以import java.util.stream.*;
(此包中的所有类)或仅import java.util.stream.Stream;
(您需要的类的 FQDN)。