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.
}
}