java map在JAVA中Map和HashMap有什么区别

java map  时间:2022-02-25  阅读:()

java中map的常用遍历方法

方法一 在for-each循环中使用entries来遍历 这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } 注意:for-each循环在java 5中被引入所以该方法只能应用于java 5或更高的版本中。如果你遍历的是一个空的map对象,for-each循环将抛出NullPointerException,因此在遍历前你总是应该检查空引用。 方法二 在for-each循环中遍历keys或values。 如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //遍历map中的键 for (Integer key : map.keySet()) { System.out.println("Key = " + key); } //遍历map中的值 for (Integer value : map.values()) { System.out.println("Value = " + value); } 该方法比entrySet遍历在性能上稍好 方法三使用Iterator遍历 使用泛型: Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } 不使用泛型: Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); System.out.println("Key = " + key + ", Value = " + value); } 方法四、通过键找值遍历(效率低) Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value); } 总结 如果仅需要键(keys)或值(values)使用方法二。 如果你使用的语言版本低于java 5,或是打算在遍历时删除entries,必须使用方法三。 否则使用方法一(键值都要)。

在JAVA中Map和HashMap有什么区别

Map是一个接口不能实例化,HashMapMap的一个实现 ,就好比你Map是一辆汽车 HashMap是宝马牌的...

Spinservers:美国圣何塞服务器,双E5/64GB DDR4/2TB SSD/10Gbps端口月流量10TB,$111/月

spinservers怎么样?spinservers大硬盘服务器。Spinservers刚刚在美国圣何塞机房补货120台独立服务器,CPU都是双E5系列,64-512GB DDR4内存,超大SSD或NVMe存储,数量有限,机器都是预部署好的,下单即可上架,无需人工干预,有需要的朋友抓紧下单哦。Spinservers是Majestic Hosting Solutions,LLC旗下站点,主营美国独立...

10gbiz:香港/洛杉矶CN2直连线路VPS四折优惠,直连香港/香港/洛杉矶CN2四折

10gbiz怎么样?10gbiz在本站也多次分享过,是一家成立于2020的国人主机商家,主要销售VPS和独立服务器,机房目前有中国香港和美国洛杉矶、硅谷等地,线路都非常不错,香港为三网直连,电信走CN2,洛杉矶线路为三网回程CN2 GIA,10gbiz商家七月连续推出各种优惠活动,除了延续之前的VPS产品4折优惠,目前增加了美国硅谷独立服务器首月半价的活动,有需要的朋友可以看看。10gbiz优惠码...

域名注册需要哪些条件(新手注册域名考虑的问题)

今天下午遇到一个网友聊到他昨天新注册的一个域名,今天在去使用的时候发现域名居然不见。开始怀疑他昨天是否付款扣费,以及是否有实名认证过,毕竟我们在国内域名注册平台注册域名是需要实名认证的,大概3-5天内如果不验证那是不可以使用的。但是如果注册完毕的域名找不到那也是奇怪。同时我也有怀疑他是不是忘记记错账户。毕竟我们有很多朋友在某个商家注册很多账户,有时候自己都忘记是用哪个账户的。但是我们去找账户也不办...

java map为你推荐
大蟒蛇平台PY平台是什么?免流量是什么意思免流量包是什么意思spotlight搜索是什么spotlight是什么意思windowsphone手机谁能给说说微软Windows phone 手机啊?色中色luntancoreldraw x6怎么抠图换背景印象城市游戏论坛凯撒大帝3怎么建造好一个城市vs2005快捷键VS2005的快捷方式是哪个文件啊?罗振宇2017跨年演讲“时间的朋友”跨年演讲办了多少场,分别是什么主题?500人同时微信如何扩大到500人群微软永久关闭实体店微软有一天倒闭了 你会怎样?
php主机空间 申请免费域名 a5域名交易 万网域名管理 z.com webhostingpad info域名 patcha 500m空间 免费个人空间 softbank邮箱 91vps qq云端 空间合租 免费智能解析 免费dns解析 360云服务 四川电信商城 lick 全能空间 更多