HashMap, HashTable, TreeMap, LinkedHashMap の違い
すべて、Mapインターフェースを実装しています。
追加した
HashMapはバラバラ
HashTableは降順
TreeMapは昇順
LinkedHashMap 追加した順
下のソースを実行すると下の結果が得られる。
java.util.HashMap 3 : c, 2 : b, 1 : a, 5 : e, 4 : d, java.util.Hashtable 5 : e, 4 : d, 3 : c, 2 : b, 1 : a, java.util.TreeMap 1 : a, 2 : b, 3 : c, 4 : d, 5 : e, java.util.LinkedHashMap 5 : e, 1 : a, 2 : b, 3 : c, 4 : d,
class StudyCollection { public static void main(String [] args){ System.out.println("hello, Collection!"); StudyCollection sc = new StudyCollection(); sc.studyHashMap(); sc.studyHashTable(); sc.studyTreeMap(); sc.studyLinkedHashMap(); } public StudyCollection(){ } public void studyHashMap(){ Map<String, String> a = new HashMap<String, String>(); this.addToMap(a); this.printMap(a); } public void studyHashTable(){ Map<String, String> a = new Hashtable<String, String>(); this.addToMap(a); this.printMap(a); } public void studyTreeMap(){ Map<String, String> a = new TreeMap<String, String>(); this.addToMap(a); this.printMap(a); } public void studyLinkedHashMap(){ Map<String, String> a = new LinkedHashMap<String, String>(); this.addToMap(a); this.printMap(a); } public void addToMap(Map<String, String> m){ m.put("5", "e"); m.put("1", "a"); m.put("2", "b"); m.put("3", "c"); m.put("4", "d"); } public void printMap(Map<String, String> m){ System.out.printf("%s\n", m.getClass().getName()); for(Iterator<String> i = m.keySet().iterator(); i.hasNext(); ){ String key = i.next(); System.out.printf("%s : %s, ", key, m.get(key)); } System.out.println(); } }
参考にしました。
Java Map クラスの違い HashMap Hashtable TreeMap LinkedHashMap