gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:51:54 25 4
gpt4 key购买 nike

看看这个.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com