软件构造——关于Map的KeySet和values方法

写在前面

在这段时间的复习和做题过程,我经常用到List,Set和Map这三个数据结构,前两个都属于容器类,我比较熟悉,而每当我使用到Map的一些方法时,我就有些不放心了,因此这篇文章主要介绍一下我对Map两个方法的疑惑与解决。

KeySet()方法

众所周知,这个方法是用来获取Map内部的包含Key的一个集合。
在这里插入图片描述
其spec是这么说的

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

翻译一下:这个方法可以返回此Map中包含的Key值的一个集合。 这个集合是由Map所支持的,因此对Map的更改会反映在集合中,反之亦然。 如果在对集合进行迭代时修改了Map(通过迭代器自己的remove操作除外),则迭代的结果不确定,也就是说这个方法是线程不安全的。 这个集合支持对元素的删除操作,该元素通过Iterator.remove,Set.remove,removeAll,retainAll和clear操作从映射中删除相应的映射。 同时,这个set不支持add或addAll操作。
下面看具体代码

		Map<String, Integer> map = new HashMap<>();
        map.put("a", 1);
        map.put("b", 2);
        Set<String> set = map.keySet();
        System.out.println(set.
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值