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方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值