问题描述
在Java中,我们可以导入单个类以及整个类(包)。
In Java we can either import single classes as well as the whole set of classes (a package).
作为示例
import java.util.*
includes
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
除了代码的长度,以任何方式使用每种方法都有任何特定的优势?内存分配?性能?
Other than the length of the code, are there any specific advantages of using the each approach in any manner? Memory allocation? Performance?
推荐答案
两者都没有性能或内存分配优势 - 它们都会编译为相同的字节码。
There is no performance or memory allocation advantage to either -- they both will compile to the same bytecode.
import
语句是告诉编译器在哪里找到源代码所引用的类。
The import
statement is to tell the compiler where to find the classes that the source code is referring to.
但是,仅按类导入是有利的。如果在两个包中有一个具有完全相同名称的类,则会引起关于引用哪个类的冲突。
However, there is an advantage to importing only by classes. If there is a class with the exact same name in two packages, there is going to be a conflict as to which class is being referred to.
一个这样的例子是 java.awt.List
class和 java.util.List
class。
One such example is the java.awt.List
class and the java.util.List
class.
假设我们要使用 java.awt.Panel
和 java.util.List
。如果源导入包如下:
Let's say that we want to use a java.awt.Panel
and a java.util.List
. If the source imports the packages as follows:
import java.awt.*;
import java.util.*;
然后,参考 List
类是将是一个暧昧的:
Then, referring to the List
class is going to be ambigious:
List list; // Which "List" is this from? java.util? java.awt?
但是,如果明确导入,则结果为:
However, if one imports explicitly, then the result will be:
import java.awt.Panel;
import java.util.List;
List list; // No ambiguity here -- it refers to java.util.List.
这篇关于Java中的类导入和包导入之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!