Map接口、HashMap、Hashtable、TreeMap类

Map 接口 映射

Map接口

1.按 “键-值”对进行插入,(键、值都是对象)可以按照键来搜索值对象
可以查找值的集合,也可以查找键的集合

2.HashMap:一种未分类,是Map的实现类,未排序的映射类,不需要顺序时HashMap是一种最好的选择,因为其效率较高,HashMap允许集合中有一个null键和多个null值。

3.Hashtable:是Map的实现类,Hashtable 是HashMap的同步版本,但Hashtable不允许有任何的null存在。

4.TreeMap:一个顺序的Map集合。

HashMap

HashMap和Hashtable类似,非同步的,并且允许null,即null value和null key 。

用法例子:

HashMap<String, Student>  map=new HashMap<String, Student>();//声明一个HashMap类型的Map
map.put("jack", new Student("王为峰", 18));//添加信息
map.put("Rose", new Student("莉莉",17));
Set<String> keys = map.keySet();
 for (String string : keys) {//forEach遍历
	 System.out.println("key:"+string+"--->value:"+map.get(string));
}

//另一种接收类型
Set<Entry<String, Student>> entryset = map.entrySet();

  for (Entry<String, Student> entry : entryset) {
	  System.out.println(entry.getKey()+entry.getValue());
}
}

HashTable

1.以键值对的形式存储数据,Hashtable是同步的,键被散列,散列码用作存储值的下标。
2.构造函数
Hashtable( )、
Hashtable(int cap)、
Hashtable(int cap, float load)、
Hashtable(Map m)、
用法例子:

Hashtable<String, Student>  map=new Hashtable<String, Student>();//声明HashTable类型的Map
map.put("jack", new Student("王为峰", 18));
map.put("Rose", new Student("莉莉",17));
	
Set<String> keys = map.keySet();
for (String string : keys) {
	  System.out.println("key:"+string+"--->value:"+map.get(string));
}

TreeMap

注:

  1. 声明形式:TreeMap<key,value> tree=new TreeMap<key,value>();
    或者:TreeMap<value,key> tree=new TreeMap<value,key>();

  2. 若value在key之前,则需要compare比较器,但是String中已经存在比较器,所以这里不用写。

用法例子:

TreeMap<Student, String> tree=new TreeMap<Student, String>();
tree.put(new Student("wangwe",18), "jack");
tree.put(new Student("wangwe",17), "jack1");
tree.put(new Student("wangwe",20), "jack2");
	
Set<Entry<Student, String>> set = tree.entrySet();
for (Entry<Student, String> entry : set) {
	System.out.println(entry.getKey()+entry.getValue());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值