在 myMap 和 myTreemap 上调用 .getClass() 时,将返回“class java.util.LinkedHashMap”和“class java.util.TreeMap”。尽管返回类型匹配,myMap 只能使用 map 接口中的方法。我听说这通过允许程序员轻松更改实现类型来简化编程。但是 - 如果我(似乎)只能访问接口中的方法,那么改变实现类型有什么好处呢?
另外 - myMap 是 myTreeMap 是根据它们的类类型排序的,但同样,类类型的方法呢?
import java.util.*;
public class Freq {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
System.out.println();
Map<String, Integer> myMap = new LinkedHashMap<String, Integer>(m);
System.out.println("map: " + myMap.getClass());
//output is "map: class java.util.LinkedHashMap"
//but, only the methods in the myMap interface can be accessed.
System.out.println(myMap.toString());
//output in order of appearance like a LinkedHashMap should.
TreeMap<String, Integer> myTreemap = new TreeMap<String, Integer>(m);
System.out.println("treemap: " + myTreemap.getClass());
//output is "treemap: class java.util.TreeMap"
//methods in the Map interface and myTreemap can be accessed.
System.out.println(myTreemap.toString());
//output in in alphabetical order like a treemap should.
}
}