Set和Map集合"/>
Set和Map集合
Set和Map集合
1、Set
1.1、无序不可以重复的
1.2、只能使用迭代器或者增强for来遍历
1.3、元素唯一
A、hashCode
(1) 、如果返回结果不同直接存储
(2) 、如果相同,继续比较equals方法
B、Equals
(1) 、地址值 || equals
(2) 、地址值相同时同一个对象不需要再调用equals方法
1.4、HashSet如何保证对象元素的唯一性
A、需要重写hashCode以及equals方法
B、只有重写这两个方法之后才能保证元素的唯一性
2、Map
2.1、HashMap
A、存储元素是以键值对的形式存储的
B、Map集合也是无序的
C、key值是唯一的
D、put方法的返回值是被替换掉的value值
2.2、常用方法
(1)、 void clear() -- 清空集合
(2)、boolean containsKey(Object key) --是否包含这个key,包含则返回 true。
(3)、V put(K key, V value) --添加元素。
(4)、V remove(Object key) --根据key删除指定的元素
(5)、 int size() --获取集合的长度。
(6)、获取功能
A、 V get(Object key) --通过key来获取对应的value值
B、 Set<K> keySet()--返回此映射中所包含的键的 Set 集合。
C、 Collection<V> values() --返回此映射所包含的值的 Collection 集合
3.2、遍历方式
A、方式一:键找值
Map<String, String> hashMap = new HashMap<>();
hashMap.put("itheima001", "迪丽热巴");
hashMap.put("itheima002", "胡歌");
hashMap.put("itheima005", "贾宝玉");
hashMap.put("itheima003", "杨幂");
hashMap.put("itheima004", "刘亦菲");
Set<String> keySet = hashMap.keySet();
for (String key : keySet) {
System.out.println(key);
System.out.println(hashMap.get(key));
}
B、方式二:Entry对象
Map<String, String> hashMap = new HashMap<>();
hashMap.put("itheima001", "迪丽热巴");
hashMap.put("itheima002", "胡歌");
hashMap.put("itheima003", "杨幂");
hashMap.put("itheima004", "刘亦菲");
hashMap.put("itheima005", "贾宝玉");
Set<Map.Entry<String, String>> entrySet = hashMap.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + "--" + entry.getValue());
}
注意:如果key是引用数据类型,如何保证key的唯一性,需要重写 hashCode以及equals方法
更多推荐
Set和Map集合
发布评论