Map接口


“集合框架”提供两种常规的Map实现:HashMapTreeMap。和所有的具体实现一样,使用哪种实现取决于特定需要

在Map中插入、删除和定位元素,HashMap是最好的选择。但如果要按顺序遍历键,那么TreeMap会更好。

使用HashMap要求添加的键类 明确定义了hashCode()实现(助理解:Map.keySet返回的是键的Set集合,而Set集合对hashCode实现有限制,因此作为键的类也要遵守该限制)。有了TreeMap实现,添加到映射的元素 一定是可排序的



一、HashMap

package cn.hncu.map;


import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;




public class MapDemo {


public static void main(String[] args) {
HashMap map=new HashMap();
map.put("1001", "张军");
map.put("1002", "张三");
map.put("1003", "王铰");
map.put("1004", "李元");
//查询1----key视图
Set keys = map.keySet();
Iterator it = keys.iterator();//是集合的查询组件
while(it.hasNext()){
String str = map.get( it.next() ).toString();
System.out.println(str);
}

   System.out.println("----------------");
//查询2----entrSet视图
   Set entry=map.entrySet();
   it = entry.iterator();//是集合的查询组件
while(it.hasNext()){
Entry e=(Entry) it.next();
System.out.println(e.getKey()+" "+e.getValue());
System.out.println(e);
}
System.out.println("----------------");
//查询2----values视图
Collection c=map.values();
it = c.iterator();//是集合的查询组件
while(it.hasNext()){
System.out.println(it.next());
}
}

}



二、TreeMap


package cn.hncu.sort;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;


public class TreeMapDemo {
public static void main(String[] args) {
TreeMap map=new TreeMap();//有排序
//HashMap map=new HashMap();没有排序
map.put("1002", "张军");
map.put("1001", "李元");
map.put("1011", "张三");
map.put("1003", "王铰");
Set set=map.entrySet();
Iterator it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值