HashSet存储自定义数据类型和LinkedHashSet集合

HashSet存储自定义数据类型

public class Test{
    /**
     * HashSet存储自定义数据类型
     * set集合保证元素唯一:存储的元素(String,Integer,Student,Person),必须重写hashCode和equals方法
     *
     * 要求:
     * 同名同龄的人,视为同一个人,只能存储一次
     */
    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<>();
        Person p1 = new Person("张三", 18);
        Person p2 = new Person("张三", 18);
        Person p3 = new Person("张三", 19);
        set.add(p1);
        set.add(p2);
        set.add(p3);

        System.out.println(p1.hashCode());//1950409828
        System.out.println(p2.hashCode());//1229416514
        System.out.println(p1 == p2);//false
        System.out.println(p1.equals(p2));//false

        set.forEach(person -> System.out.println(person));

    }
}

class Person{
    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

LinkedHashSet集合

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

        LinkedHashSet<String> linked = new LinkedHashSet<>();
        linked.add("www");
        linked.add("abc");
        linked.add("abc");
        linked.add("4399");
        System.out.println(linked);//[www, abc, 4399] 有序;不允许重复
    }
}
posted @ 2022-07-06 09:25  我滴妈老弟  阅读(36)  评论(0编辑  收藏  举报