1.J2SDK API中提供HashSet
2.若要根据根据自定义类型自身的属性来确定集合元素的唯一性需要重写 equals()和hashCode()两方法。
* 向HashSet添加对象时HashSet先通过该对象的hashCode()方法计算出相应的的桶,然后在根据equals()方法找到相应的对象,如果容器中已经存在该对象则不再添加,如果不存在则添加进去
import java.io.Serializable;
public class Student implements Serializable, Comparable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Object o) {
if(!(o instanceof Student)){
throw new ClassCastException("object to cast student error !");
}
return this.age - ((Student)o).age;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student)){
throw new ClassCastException("object to cast student error !");
}
return this.name ==((Student)obj).name;
}
}
import java.util.HashSet;
public class Main {
public static void main(String []args){
HashSet<Student> hs = new HashSet<Student>();
for(int i = 0; i< 10; i++){
hs.add(new Student("AA"+i, -i + 10));
}
System.out.println(hs);
}
}