HashMap和TreeMap的区别

时间:2021-05-14 16:47:45

HashMap通过hashcode对其内容进行快速查找,而 TreeMap中所有的元素都保持着某种固定的顺序,如果你需要得到一个有序的结果你就应该使用TreeMap(HashMap中元素的排列顺序是不固定的)。Hashmap适用于在Map中插入,删除,和定位元素。

HashMap 非线程安全 TreeMap 非线程安全

下面代码演示了HashMap和TreeMap的使用

HashMap:

public class HashMapDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, Integer> hashMap=new HashMap<String, Integer>();
hashMap.put("Com", new Integer(24));
hashMap.put("Aane", new Integer(21));
hashMap.put("Back", new Integer(21));
hashMap.put("Dazz", new Integer(23));
//获取Entry的集合
Set<Map.Entry<String, Integer>> set=hashMap.entrySet();
for (Entry<String, Integer> entry : set) {
System.out.println(entry);

}
System.out.println("-------------------------");
//获取键集
Set<String> keySet=hashMap.keySet();
StringBuffer buffer=new StringBuffer("");

for (String string : keySet) {
buffer.append(string+",");
}
String string=buffer.substring(0,buffer.length()-1);
System.out.println(string);
}
/**运行结果为
Com=24Aane=21Back=21Dazz=23-------------------------Com,Aane,Back,Dazz
可以看出HashMap为无序的*/}
TreeMap:

public class TreemapDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

TreeMap<String, Integer> TreeMap=new TreeMap<String, Integer>();
TreeMap.put("Com", new Integer(24));
TreeMap.put("Aane", new Integer(21));
TreeMap.put("Back", new Integer(21));
TreeMap.put("Dazz", new Integer(23));
//获取Entry的集合
Set<Map.Entry<String, Integer>> set=TreeMap.entrySet();
for (Entry<String, Integer> entry : set) {
System.out.println(entry.getKey()+":"+entry.getValue());

}
System.out.println("-------------------------");
//获取键集
Set<String> keySet=TreeMap.keySet();
StringBuffer buffer=new StringBuffer("");

for (String string : keySet) {
buffer.append(string+",");
}
String string=buffer.substring(0,buffer.length()-1);
System.out.println(string);
}
/**
运行结果根据Key进行排序
Aane:21Back:21Com:24Dazz:23-------------------------Aane,Back,Com,Dazz
*/}