为什么我不必导入一些类? [英] Why don't I have to import some classes?

查看:93
本文介绍了为什么我不必导入一些类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 .java 文件:

class A {
    HashMap a;
}

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

It doesn't compile; I need to import java.util.HashMap;. Now consider this one:

class A {
    String a;
}

完全相同 - 除了 String 而不是 HashMap - 所以它不应该编译,对吧?错了。

It's exactly the same—except with String instead of HashMap—so it shouldn't compile, right? Wrong.

好的,所以众所周知,你不必导入 String ,但为什么是那个? 显而易见的答案是因为 String 的使用频率远远超过 HashMap ,但不应该 ArrayList 被隐式导入?原始包装类如何,例如整数布尔 ArrayList 使用 Long Float <更多/ code>,但我必须导入 ArrayList ,而不需要导入 Float

Okay, so it's pretty well-known that you don't have to import String, but why is that? The "obvious" answer is because String is used far more often than HashMap, but then shouldn't ArrayList be "implicitly imported"? What about the the primitive wrapper classes, e.g. Integer and Boolean? ArrayList is used far more often than Long and Float, but I have to import ArrayList and don't need to import Float.

不需要导入的原因是什么字符串整数字符异常以及其他一些类?

What is the reason behind not needing to import String, Integer, Character, Exception and a few other classes?

推荐答案


显而易见的答案是因为 String 的使用频率远高于 HashMap

否。 String 属于 java.lang 包,由编译器自动导入。

No. String belongs to java.lang package, which is automatically imported by the compiler.

来自 java.lang javadoc:

From java.lang javadoc:


提供设计基础的类Java编程语言。最重要的类是 Object ,它是类层次结构的根, Class ,其实例代表类在运行时。

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语言规范。第7章软件包


软件包由许多编译单元组成(§7.3)。编译单元自动访问其包中声明的所有类型,并自动导入在预定义包中声明的所有 public 类型 java.lang

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.

这篇关于为什么我不必导入一些类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆