首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

HashMap 跟TreeMap的比较

2012-12-25 
HashMap 和TreeMap的比较HashMap 和TreeMap的比较与Java相关信息HashMap的代码为: import java.util.* pu

HashMap 和TreeMap的比较
HashMap 和TreeMap的比较
与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大,因为它要处理排序!

热点排行