我们在Java中经常使用的即为HashMap,基于哈希表进行实现,其内部是无序的,非线程安全,所以速度较快。
LinkedHashMap基于 哈希表+链表进行实现,其顺序是put的顺序来排序,即先入排在最前面,非线程安全TreeMap基于 红黑树进行实现,其内部是有序的,排序规则是安全其中key实现的compareable接口来进行排序,非线程安全
Hashtable与HashMap类似,基于 哈希表进行实现,方法加入 synchronized,内部无序,线程安全,速度较慢
一、HashMap:
People people1 = new People(18, "name1");
People people2 = new People(25, "name2");
People people3 = new People(16, "name3");
// hashMap
HashMap<People, String> hashMap = new HashMap<>();
hashMap.put(people1, "a");
hashMap.put(people2, "b");
hashMap.put(people3, "c");
Iterator<Map.Entry<People, String>> hashMapIterator = hashMap.entrySet().iterator();
while (hashMapIterator.hasNext()){
People people = hashMapIterator.next().getKey();
System.out.println("年龄为" + people.getAge());
}
结果为:
年龄为25
年龄为18
年龄为16
可以看到是无序的。
二、LikedHashMap:
LinkedHashMap<People, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put(people1, "a");
linkedHashMap.put(people2, "b");
linkedHashMap.put(people3, "c");
Iterator<Map.Entry<People, String>> linkedHashMapIterator = linkedHashMap.entrySet().iterator();
while (linkedHashMapIterator.hasNext()){
People people = linkedHashMapIterator.next().getKey();
System.out.println("年龄为" + people.getAge());
}
年龄为18
年龄为25
年龄为16
三、TreeMap:
TreeMap<People, String> treeMap = new TreeMap<>();
treeMap.put(people1, "a");
treeMap.put(people2, "b");
treeMap.put(people3, "c");
Iterator<Map.Entry<People,String>> iterator = treeMap.entrySet().iterator();
while (iterator.hasNext()) {
People people = iterator.next().getKey();
System.out.println("年龄为" + people.getAge());
}
结果为:
年龄为16
年龄为18
年龄为25
可以看到,按照People的Comparable来进行排序
四、Hashtable:
Hashtable<People, String> hashtable = new Hashtable<>();
hashtable.put(people1, "a");
hashtable.put(people2, "b");
hashtable.put(people3, "c");
Iterator<Map.Entry<People, String>> hashTableIterator = hashtable.entrySet().iterator();
while (hashTableIterator.hasNext()){
People people = hashTableIterator.next().getKey();
System.out.println("年龄为" + people.getAge());
}
返回值为:
年龄为16
年龄为25
年龄为18
可见也是无序的。