HashMap和TreeMap是实现了Map接口的两个类,前者为无序的Map,后者为有序的Map。下面通过程序来看这种有序和无序的区别。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class MapTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,String> hm = new HashMap<String,String>();
Map<String,String> tm = new TreeMap<String,String>();
//初始化数据
for(int i=0;i<5;i++){
hm.put("key"+i, "Value"+i);
tm.put("key"+i, "Value"+i);
}
hm.put("cc", "其他键值对cc");
hm.put("ee", "其他键值对ee");
hm.put("aa", "其他键值对aa");
tm.put("cc", "其他键值对cc");
tm.put("ee", "其他键值对ee");
tm.put("aa", "其他键值对aa");
Iterator<?> it_hm = hm.entrySet().iterator();
Iterator<?> it_tm = tm.entrySet().iterator();
System.out.println("\n=======遍历输出HashMap的内容=======\n");
while(it_hm.hasNext()){
Entry<?, ?> obj = (Entry<?, ?>)it_hm.next();
System.out.println(obj.getKey()+" "+obj.getValue());
}
System.out.println("\n=======遍历输出TreeMap的内容=======\n");
while(it_tm.hasNext()){
Entry<?, ?> obj = (Entry<?, ?>)it_tm.next();
System.out.println(obj.getKey()+" "+obj.getValue());
}
hm.remove("cc");
tm.remove("cc");
it_hm = hm.entrySet().iterator();
it_tm = tm.entrySet().iterator();
System.out.println("\n=======删除后遍历输出HashMap的内容=======\n");
while(it_hm.hasNext()){
Entry<?, ?> obj = (Entry<?, ?>)it_hm.next();
System.out.println(obj.getKey()+" "+obj.getValue());
}
System.out.println("\n=======删除后遍历输出TreeMap的内容=======\n");
while(it_tm.hasNext()){
Entry<?, ?> obj = (Entry<?, ?>)it_tm.next();
System.out.println(obj.getKey()+" "+obj.getValue());
}
}
}
运行结果:
=======遍历输出HashMap的内容=======
key4 Value4
key3 Value3
ee 其他键值对ee
key0 Value0
key2 Value2
key1 Value1
aa 其他键值对aa
cc 其他键值对cc
=======遍历输出TreeMap的内容=======
aa 其他键值对aa
cc 其他键值对cc
ee 其他键值对ee
key0 Value0
key1 Value1
key2 Value2
key3 Value3
key4 Value4
=======删除后遍历输出HashMap的内容=======
key4 Value4
key3 Value3
ee 其他键值对ee
key0 Value0
key2 Value2
key1 Value1
aa 其他键值对aa
=======删除后遍历输出TreeMap的内容=======
aa 其他键值对aa
ee 其他键值对ee
key0 Value0
key1 Value1
key2 Value2
key3 Value3
key4 Value4
本文通过实例演示了HashMap与TreeMap两种数据结构在Java中的使用区别。HashMap存储无序键值对,而TreeMap则自动对键进行排序。示例展示了插入、遍历及删除操作后的不同表现。
705

被折叠的 条评论
为什么被折叠?



