文章目录
写在前面
在这段时间的复习和做题过程,我经常用到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.