下面是一個例子:爲什麼我不必在Java中導入不用作變量類型的類?
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編譯器如何知道map.keySet()
在不導入java.util.Set的情況下返回什麼?
我在其他編程語言中也見過這種行爲,特別是C++。