看看这个.java
文件:
class A {
HashMap a;
}
它无法编译;我需要import java.util.HashMap;
。现在考虑这个:
class A {
String a;
}
完全一样——除了String
而不是HashMap
——所以它不应该编译,对吧?错了。
好吧,众所周知,您不必导入 String
,但是为什么是这样呢? “显而易见”的答案是因为String
使用频率远高于 HashMap
,但不应该ArrayList
是“隐式导入”吗?原始包装类怎么样,例如Integer
和Boolean
? ArrayList
比 Long
使用频率远和Float
,但我必须导入 ArrayList
并且不需要导入Float
.
不需要导入String
的原因是什么? , Integer
, Character
, Exception
还有其他一些类(class)?
最佳答案
The obvious answer is because
String
is used far more often thanHashMap
.
没有。 String
属于java.lang
包,由编译器自动导入。
来自java.lang
javadoc:
Provides classes that are fundamental to the design of the Java programming language. The most important classes are
Object
, which is the root of the class hierarchy, andClass
, instances of which represent classes at run time.
来自 Java Language Specification. Chapter 7. Packages
A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the
public
types declared in the predefined packagejava.lang
.
关于java - 为什么我不必导入一些类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703328/