关于set
public static void main(String[] args) { //创建一个集合set对象 //Set<Student> set = new TreeSet<Student>(); //Set<Student> set = new HashSet<Student>(); Set<Student> set = new LinkedHashSet<Student>(); //添加多个学生 Student stu2 = new Student(2, "lisi", 23, 98); Student stu3 = new Student(3, "wangwu", 22, 87); Student stu1 = new Student(1, "zhangsan", 23, 90); Student stu4 = new Student(1, "zhangsan", 23, 90); set.add(stu1); set.add(stu2); set.add(stu3); set.add(stu4); //输出学生 System.out.println(set.size()); System.out.println(set); }
问题1:HashSet、LinkedHashSet :为什么String有重复,会保持唯一;为什么Student有重复,不会保持唯一。
问题2:TreeSet 为什么String可以添加,而Student就不让添加到TreeSet中呢? 而是抛出异常:
java.lang.ClassCastException: com.bjsxt.entity.Student cannot be cast to java.lang.Comparable
思考:String是系统类,Student是自定义类,应该是String已经做了某些事情,但是Student没有做
解答1:HashSet、LinkedHashSet 需要Student实现hashCode()和equals()
解答2:TreeSet 需要Student实现Comparable接口并指定比较的规则
public class Student implements Comparable<Student>{ private int sno; private String name; private int age; private double score; @Override public int compareTo(Student o) { //return this.sno - o.sno; //return o.sno - this.sno; return -(this.sno - o.sno); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; if (sno != student.sno) return false; if (age != student.age) return false; if (Double.compare(student.score, score) != 0) return false; return name != null ? name.equals(student.name) : student.name == null; } @Override public int hashCode() { int result; long temp; result = sno; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + age; temp = Double.doubleToLongBits(score); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }