这是一个例子:
import java.util.HashMap;
public class Test
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("leorum", 1);
map.put("ipsum", 2);
map.put("dolor", 3);
System.out.println(map.keySet().toString());
}
}
一切都编译并运行良好。但是,当我将 map.keySet()
移动到另一个变量时:
import java.util.HashMap;
public class Test
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("leorum", 1);
map.put("ipsum", 2);
map.put("dolor", 3);
Set<String> keys = map.keySet();
System.out.println(keys.toString());
}
}
我收到一个错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Set cannot be resolved to a type
at Test.main(Test.java:12)
我明白为什么我在第二个例子中会出错,但为什么我在第一个例子中没有出错? java 编译器如何在不导入 java.util.Set 的情况下知道 map.keySet()
返回什么?
我在其他编程语言中也看到过这种行为,尤其是 C++。
最佳答案
I understand why I get an error for the second example, but why don't I get an error for the first? How does the java compiler know what
map.keySet()
returns without importingjava.util.Set
?
无论哪种方式,它都知道 - 它是字节码中元数据的一部分。
它不知道你所说的 Set<String>
是什么意思.导入只会更改源代码中某个名称的含义 - 而该名称不会出现在源代码的第一段代码中。
An import declaration allows a named type or a static member to be referred to by a simple name (§6.2) that consists of a single identifier.
您没有在第一个示例中引用简单名称,因此上述好处无关紧要。
换句话说,导入只允许这一行(这在您的第二个示例中有效):
java.util.Set<String> keys = map.keySet();
写成:
Set<String> keys = map.keySet();
这就是它所做的一切。
关于java - 为什么我不必导入在 Java 中不用作变量类型的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552470/