Java集合之HashMap

HashMap是最常用的Map集合,它的键值对在存储时要根据键的哈希码来确定值放在哪里。

HashMap 中作为键的对象必须重写Object的hashCode()方法和equals()方法


import java.util.Map;
import java.util.HashMap;
public class lzwCode {

	public static void main(String [] args) {
		
		Map<Integer, String> map = new HashMap<Integer, String>();
		map.put(1, "Barcelona");
		map.put(2, "RealMadrid");
		map.put(3, "ManchesterUnited");
		map.put(4, "AC milan");
		map.put(5, null);
		map.put(null, null);
		//map.put(null, "Chelsea"); //可以运行键值都为空(如果键相同,后者覆盖前者)
		System.out.println(map);
		System.out.print(map.keySet()+" "); //集合中所有键以Set集合形式返回
		System.out.println();
		System.out.print(map.values()+" "); //集合中所有键以Collection集合形式返回
		System.out.println();
		System.out.println("集合大小:"+map.size());
		System.out.println("是否包含该键:"+map.containsKey(2));//返回boolean
		System.out.println("是否包含该值:"+map.containsValue("Barcelona"));//返回boolean
		System.out.println(map.isEmpty()); //不包含键-值映射关系,则返回true
		map.remove(5); //删除映射关系
		System.out.println(map);
		map.clear();//清空集合
		System.out.println(map);
	}
}

控制台结果:



HashMap的两种遍历方法

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class lzwCode {

	public static void main(String [] args) {
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("Barcelona", 1);
		map.put("RealMadrid", 2);
		map.put("ManchesterUnited", 3);
		map.put("AC milan", 4);
		map.put("Chelsea", 5);
		//第一种:(效率高)
		System.out.println("第一种方法:");
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry)iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			System.out.println("键:"+key+"<==>"+"值:"+val);
		}
		//第二种:(效率低)
		System.out.println("第二种方法:");
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			Object key = it.next();
			Object val = map.get(key);
			System.out.println("键:"+key+"<==>"+"值:"+val);
		}
		//对于keySet只是遍历了2次,一次是转为iterator,一次就从HashMap中取出key所对于的value。
        //对于entrySet只是遍历了第一次,它把key和value都放到了entry中,所以快比keySet快些。
		System.out.println("For-Each循环输出");
		//For-Each循环
		for (Map.Entry<String, Integer> entry:map.entrySet()) {
			String key = entry.getKey().toString();
			String val = entry.getValue().toString();
			System.out.println("键:"+key+"<==>"+"值:"+val);
		}
	}
}

控制台结果:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值