HashSet存储自定义类型元素和LinkedHashSet集合

HashSet集合存储自定义类型元素

HashSet存储自定义类型元素

set集合报错元素唯一:

      ~存储的元素(String,Integer,…Student,Person…)必须重写hashCode方法和equals方法

要求:同名同年龄的人,视为同一个人,只能存储一次

复制代码
public static void main(String[] args) {
//创建HashSet集合存储Person
HashSet<Person> set = new HashSet<>();
Person p1 = new Person("小美女",18);
Person p2 = new Person("小美女",18);
Person p3 = new Person("小美女",19);
System.out.println(p1.hashCode());//734175839
System.out.println(p2.hashCode());//734175839

System.out.println(p1==p2);//false
System.out.println(p1.equals(p2));//true
set.add(p1);
set.add(p2);
set.add(p3);
System.out.println(set);//[Person{name='小美女', age=19}, Person{name='小美女', age=18}]
}
复制代码

LinkedHashSet集合

  • java.util.LinkedHashSet集合 extends HashSet集合
  • LinkedHashSet集合特点:
  • 底层是一个哈希表(数组+链表/红黑树)+链表:多了一条链表(记录元素的存储顺序),保证元素有序
复制代码
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("www");
set.add("abc");
set.add("itcast");
System.out.println(set);//[abc, www, itcast]

LinkedHashSet<String> linked = new LinkedHashSet<>();
linked.add("www");
linked.add("abc");
linked.add("itcast");
System.out.println(linked);//[www, abc, itcast]
}
复制代码

 

posted @   夫君  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示