使用Set存儲Object對象,重寫equals和hashCode方法

概念

Set接口繼承Collection接口,用來包含一組無序無重複的對象,它的常用實現類有HashSet(內部對象是散列存取,採用哈希技術)、TreeSet(存儲的數據是升序的)

下面以HashSet測試Set存儲

Studnet.java
public class Student {
private String id;
private String name;

public Student(String id, String name) {
    super();
    this.id = id;
    this.name = name;
}

public String getId() {
    return id;
}

public String getName() {
    return name;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        System.out.println("true");
        return true;
    }
    if ((obj == null) || (obj.getClass() != this.getClass())) {
        System.out.println("false");
        return false;
    }
    if (id == ((Student) obj).id && name == ((Student) obj).name) {
        return true;
    } else {
        return false;
    }
    }

@Override
public int hashCode() {
    int flag = 36;
    int idNum = Integer.parseInt(id);
    return flag * idNum;
}
}
HashSetTest.java
import java.util.HashSet;
import java.util.Set;

public class HashSetTest {

public static void main(String[] args) {
    Student s1=new Student("1","li");
    Student s2=new Student("2","ji");
    Student s3=new Student("3","ji");
    Student s4=new Student("3","ji");
    Set<Student> hs=new HashSet<>();
    hs.add(s1);
    hs.add(s2);
    hs.add(s3);
    hs.add(s4);
    for (Student student : hs) {
        System.out.println(student.getId()+":"+student.getName());
    }
}

}

運行結果:
1:li
2:ji
3:ji

分析

要使用Set存儲Object的對象,執行add方法的時候,會先判斷equals方法是否與已有的值相等,再判斷是否有相同的hash值,若這兩個方法結果都爲true,則這個對象就認爲已經存在,不插入,所以,我們要對equals和hashCode方法進行重寫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章