HashSet类的概述
HashSet类实现了Set接口;
HashSet容器的元素是无序的不能重复的;
存放入HashSet容器中的类必须要实现equals()和hashCode()方法;
什么类需要重写equals()和hashCode()方法
Hashtable、HashSet、HashMap都必须同时实现equals()和hashCode()方法;
TreeSet、TreeMap则不需要实现equals()和hashCode()方法;
为什么要重写equals()和hashCode()方法
Object中的hashCode()方法会返回该对象的内存真实地址的整数化表示,这个返回的不是真正地址的整数值,是哈希码;
向HashSet中添加对象时,HashSet先通过该对象的hashCode()计算出相应的的值,然后再根据equals()方法找到相应的对象。如果容器中已经存在该对象则不再添加,如果不存在则添加进去;
怎么重写equals()和hashCode()方法
public boolean equals(Objeat obj){
如果this和obj的内容一模一样
返回true
否则
返回false
}
public int hashCode(){
返回 当前类中基本数据类型对象的hashCode()方法
}
import java.util.*;
public class TestHashSet{
public static void main(String[] args) {
Set se=new HashSet();
se.add(new Student_2(11,"小明"));
se.add(new Student_2(22,"小红"));
se.add(new Student_2(22,"小红"));
se.add(new Student_2(22,"小红"));
se.add(new Student_2(22,"小红"));
se.add(new Student_2(22,"小红"));
se.add(new Student_2(22,"小红"));
se.add(new Student_2(33,"小啥"));
System.out.println(se);
}
}
class Student_2{
private int age;
private String name;
public Student_2(int age,String name) {
this.age=age;
this.name=name;
}
public String toString() {
return "age:"+age+" "+"name:"+name;
}
public boolean equals(Object obj) {
Student_2 st=(Student_2)obj;
return this.age==st.age && this.name.equals(st.name);
}
public int hashCode() {
return age+this.name.hashCode();
}
}
输出结果:[age:11 name:小明, age:22 name:小红, age:33 name:小啥]