在學習HashSet之前我們很有必要了解一下哈希值
哈希值
哈希值: 根據對象的地址或者字符串或者數字算出來的int類型的數值
Object類中有一個方法可以獲取對象的哈希值
方法名 | 說明 |
---|---|
public int hashCode() | 返回對象的哈希碼值 |
對象的哈希值特點
- 爲保證元素唯一性,需要重寫hashcode()和equals()(自己創建的實體類需要注意)
- 同一個對象多次調用hashCode0方法返回的哈希值是相同的
- 默認情況下, 不同對象的哈希值是不同的。而重寫hashCode0方法,可以實現讓不同對象的哈希值相同
HashSet集合概述和特點
- 底層數據結構是哈希表
- 對集合的迭代順序不作任何保證,也就是說不保證存儲和取出的元素順序一致
- 沒有帶索引的方法,所以不能使用普通for循環遍歷
- 由於是Set集合, 所以是不包含重複元素的集合
重寫hashcode()和equals()
沒有重寫hashcode()和equals():
重寫hashcode()和equals()之後:
重寫兩個方法代碼實例
測試類:
import java.util.*;
public class Dmeo {
public static void main(String[] args) {
Student student1 = new Student("小哲哲",18);
Student student2 = new Student("小哲",17);
Student student3 = new Student("小哲哲",18);
Set<Student> set = new HashSet<Student>();
set.add(student1);
set.add(student2);
set.add(student3);
for(Student s : set) {
System. out . println(s.getName()+s.getAge());
}
}
}
學生類:(最下方兩行代表重寫方法,可一鍵生成)
public class Student {
private String name;
private Integer age;
public Student(String s,int i) {
this.name = s;
this.age = i;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
hashSet集合元素添加過程
- 調用對象的hashCode()方法獲取對象的哈希值,根據對象的哈希值計算對象的存儲位置。
- 該位置是否有元素存在
沒有,存儲到該位置,結束;
有,判斷下一條; - 遍歷該位置的所有元素,和新存入的元素比較哈希值是否相同
都不相同,存儲到該位置,結束;
有相同的,判斷下一條; - 調用equals()方法比較對象內容是否相等
返回false,將元素存儲到該位置;
否則說明元素重複,不存儲;