zoukankan      html  css  js  c++  java
  • 关于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;
            }
        }
  • 相关阅读:
    虚拟主机的陷阱
    http://www.xmenglish.com/(外贸知识网站)
    Highlight Table Row
    让你从电脑维修新手到高手
    Flash 视频教程
    ASP Comparison Operators Logical Operators
    Linux 虚拟机 NAT方式上网设置
    vim技巧
    25 条 SSH 命令和技巧
    linux下添加路由的方法
  • 原文地址:https://www.cnblogs.com/vincentmax/p/14241928.html
Copyright © 2011-2022 走看看