java - 为什么我不必导入一些类?

标签 java import

看看这个.java文件:

class A {
    HashMap a;
}

它无法编译;我需要import java.util.HashMap; 。现在考虑这个:

class A {
    String a;
}

完全一样——除了String而不是HashMap ——所以它不应该编译,对吧?错了。

好吧,众所周知,您不必导入 String ,但是为什么是这样呢? “显而易见”的答案是因为String使用频率远高于 HashMap ,但不应该ArrayList是“隐式导入”吗?原始包装类怎么样,例如IntegerBooleanArrayListLong 使用频率Float ,但我必须导入 ArrayList并且不需要导入Float .

不需要导入String的原因是什么? , Integer , Character , Exception还有其他一些类(class)?

最佳答案

The obvious answer is because String is used far more often than HashMap.

没有。 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, and Class, 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 package java.lang.

关于java - 为什么我不必导入一些类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703328/

相关文章:

excel - XtraReports 以编程方式设置 Excel 导入单元格格式

javascript - 如何在 Node JS 中正确使用 import

java - 如何使用 java.util.zip 制作 epub

java - 将控制从被调用者 servlet 发送回调用者 jsp

java - 带有显示标签的 struts 1.3 磁贴

java - 如何在 NetBeans 中正确导入 Apache HttpClient?

java - Java 中的@Override 注解

java - 在java中构建rest api时使用servlet有什么优点

python - 在 Python 中处理多个代码文件和文件夹

json - 如何以编程方式将 JSON 文件导入 MATLAB?