java - 为什么我不必导入在 Java 中不用作变量类型的类?

标签 java class import

这是一个例子:

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 importing java.util.Set?

无论哪种方式,它都知道 - 它是字节码中元数据的一部分。

它不知道你所说的 Set<String> 是什么意思.导入只会更改源代码中某个名称的含义 - 而该名称不会出现在源代码的第一段代码中。

来自 section 7.5 of the JLS :

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/

相关文章:

java - getDownloadUrl 函数未返回正确的 url

java - 可重入锁和同步的实现有何不同

C++ 类作用域

typescript - 如何在构造之前定义可在类上使用的属性(例如,用于工厂方法)?

javascript - 如何在 JavaScript 中声明 ClassName.FunctionName.myFunction() ?

java - 如何将 Keras Tokenizer 导入 Java Deeplearning4j (DL4J)

Java:在静态方法中从父类(super class)创建子类的实例

java - Spring Cloud Gateway 的 LDAP 身份验证

javascript - 如何在 Node.js 中使用第二个构造函数的变量? (使用导入/导出)

python - C -> Python 导入包装器问题