【HashSet:重寫比較方法示例一】

package com.yjf.esupplier.common.test;

import java.util.HashSet;

/**
 * @author shusheng
 * @description
 * @Email shusheng@yiji.com
 * @date 2018/12/14 14:11
 */
public class HashSetDemo {
    /**
     * 需求:存儲自定義對象,並保證元素的惟一性
     * 要求:若是兩個對象的成員變量值都相同,則爲同一個元素。
     * 
     * 目前是不符合要求的:由於咱們知道HashSet底層依賴的是hashCode()和equals() 方法
     * 而這兩個方法咱們在學生類中沒有重寫,因此,默認使用的是Object類的。
     * 這個時候,他們的哈希值是不同的,根本就不會繼續判斷,執行了添加操做。
     */
    public static void main(String[] args) {
        //建立集合對象
        HashSet<Student> hs = new HashSet<Student>();
        Student s1 = new Student("林青霞", 27);
        Student s2 = new Student("王祖賢", 21);
        Student s3 = new Student("柳巖", 23);
        Student s4 = new Student("林青霞", 27);
        Student s5 = new Student("范冰冰", 32);
        Student s6 = new Student("林青霞", 27);

        //添加元素hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);
        hs.add(s5);
        hs.add(s6);

        for (Student s : hs) {
            System.out.println(s.getName() + "---" + s.getAge());
        }
    }
}

class Student {

    private String name;
    private int age;

    public Student(String name, int age) {
        super();
        this.name = name;
        this.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;
    }

    /**
     * 若是對象的哈希值相同了,就會走equals()方法進行比較對象的成員變量是否相同
     * 若是不一樣,就添加到集合,若是相同,就不添加
     * 哈希表:是一個元素爲鏈表的數組,綜合了數組和鏈表的好處。如何優化代碼:
     * 讓對象的哈希值儘量的不一樣。哈希值和哪些內容相關呢?
     * 和對象的成員變量值相關。
     * 因此,咱們的最終解決方法就是把對象的成員變量值進行相加: 若是是基本類型,就直接加值。
     * 若是是引用類型,就加哈希值。
     */
    @Override
    public int hashCode() {
        return this.name.hashCode() + this.age * 113;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Student)) {
            return false;
        }

        Student s = (Student) obj;
        return this.name.equals(s.name) && this.age == s.age;
    }

}
相關文章
相關標籤/搜索