Hashset特点
hash算法来存储集合中元素,具有很好的存取和查找性能
不保证set的迭代顺序
HashSet不是同步的,无法再多线程保持一致性
元素可以为null
HashSet进行存储时,会先调用hashCode()获取hash值,然后根据该值确定在HashSet中的存储位置。
在HashSet中,不能存在两个相等的元素,通过内部的equals()来判断是否相等
Hashset去重方法
public class Car {
private Stringname;
private int price;
//重写hashCode方法
public int hashCode(){
System.out.println(this.name+".....hashCode");
return this.name.hashCode()+this.price;
}
//重写equals方法
public boolean equals(Object obj){
if (this == obj){
return true;
}
if (obj ==null || getClass() != obj.getClass()){
return false;
}
Car p=(Car)obj;
System.out.println(this.name+"..equals.."+p.name);
return this.name.equals(p.name) &&this.price==p.price;
}
}