HashSet
HashSet 是一个集合,该集合的作用是去重。
import java.util.HashSet;
public class Test {public static void main(String[] args) {HashSet hashSet = new HashSet();People people1 = new People();People people2 = new People();hashSet.add("hello");hashSet.add("hello");System.out.println(hashSet);}
}
hashCode
hashCode 是一个本地方法,它的作用是将对象转化为一个 int 类型的地址,然后根据 int 类型的地址是否相同判断变量是否相同。
重写 equals() 方法后必须重写 hashCode() 方法。
public class People {private int age;public People(int age) {this.age = age;}//重写equals()方法public boolean equals(People otrP) {if (this.age == otrP.age) {return true;}return false;}
}
import java.util.HashSet;
public class Test {public static void main(String[] args) {HashSet hashSet = new HashSet();People people1 = new People(18);People people2 = new People(18);System.out.println(people1.equals(people2));hashSet.add(people1);hashSet.add(people2);System.out.println(hashSet);}
}