[b]HashMap 和TreeMap的比较[/b]
与Java相关信息
HashMap的代码为:
HashTree的代码:
但是TreeMap的开销也比较HashMap大,因为它要处理排序!
与Java相关信息
HashMap的代码为:
import java.util.*;
public class hashmap {
Map calendar = new HashMap();
public hashmap(String d[],String i[]){
for(int j=0;j<d.length;j++){
calendar.put(d[j], i[j]);
}
}
public static void main(String[] args) {
String [] dates = {"10/4","05/7","12/7","01/5"};
String [] items = {"Z","Y","X","C"};
hashmap example = new hashmap(dates,items);
Set mapping = example.calendar.entrySet();
System.out.println("map= "+example.calendar);
System.out.println("Object\tkey\tvalue");
for(Iterator it = mapping.iterator();it.hasNext();){
Map.Entry me = (Map.Entry)it.next();
Object ok = me.getKey();
Object ov = me.getValue();
System.out.print(me+"\t");
System.out.print(ok+"\t");
System.out.println(ov);
}
}
}
HashTree的代码:
import java.util.*;
public class hashmap {
Map calendar = new TreeMap();
public hashmap(String d[],String i[]){
for(int j=0;j<d.length;j++){
calendar.put(d[j], i[j]);
}
}
public static void main(String[] args) {
String [] dates = {"10/4","05/7","12/7","01/5"};
String [] items = {"Z","Y","X","C"};
hashmap example = new hashmap(dates,items);
Set mapping = example.calendar.entrySet();
System.out.println("map= "+example.calendar);
System.out.println("Object\tkey\tvalue");
for(Iterator it = mapping.iterator();it.hasNext();){
Map.Entry me = (Map.Entry)it.next();
Object ok = me.getKey();
Object ov = me.getValue();
System.out.print(me+"\t");
System.out.print(ok+"\t");
System.out.println(ov);
}
}
}
代码大致相同,但是HashMap的输出是无序的,TreeMap的输出是按关键字升序排列的!但是TreeMap的开销也比较HashMap大,因为它要处理排序!