Set HashSet

package com.dh.learn.collection;

import java.util.HashSet;
import java.util.Set;

public class LearnHashSet {
    public static void main(String[] args) {
        Set<Person> set = new HashSet<>();
        set.add(new Person("dh", 12));
        set.add(new Person("dh", 12));
        set.add(new Person("dh2", 12));
        set.add(new Person("dh3", 12));

        // set中有四个元素,乱序,与插入顺序无关。
        // 因为Person没有重写hashCode方法,所以会有两个dh-12的Person,因为他们的内存地址不同。
        // HashSet内部其实是用HashMap的key来实现的。
        for (Person person : set) {
            System.out.println(person);
        }

        // 重写hashcode方法之后,Set就可以判断BMW-10.0 是同一个元素啦
        Set<Car> cars = new HashSet<>();
        cars.add(new Car("BMW", 10.0f));
        cars.add(new Car("BMW", 10.0f));
        cars.add(new Car("BYD", 9.0f));
        cars.add(new Car("ASLS", 11.0f));

        for (Car car : cars) {
            System.out.println(car);
        }


        //TreeSet会按照元素顺序排序。是用TreeMap的key实现的。
    }

    static class Person {
        String name;
        int age;

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

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

        @Override
        public boolean equals(Object obj) {
            return this.toString().equals(obj.toString());
        }
    }

    static class Car {
        String name;
        float price;

        public Car(String name, float price) {
            this.name = name;
            this.price = price;
        }

        @Override
        public String toString() {
            return name + "===" + price;
        }

        @Override
        public boolean equals(Object obj) {
            return this.toString().equals(obj.toString());
        }

        @Override
        public int hashCode() {
            return name.hashCode();
        }
    }
}

 

posted on 2019-08-12 17:36  李笑白  阅读(96)  评论(0编辑  收藏  举报

导航