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;
            }
        }
  • 相关阅读:
    美剧天堂前100最新
    自动登录github
    分布式爬虫
    爬虫框架:scrapy
    First day ~
    docker 使用的一些笔记
    POI 写出word文档实例
    POI 生成word各类问题(设置中文字体,重复图片插入等怪问题......)
    HTML 与 文本 的相互转义
    TDengine + Telegraf + Grafana 运维监测系统搭建
  • 原文地址:https://www.cnblogs.com/vincentmax/p/14241928.html
Copyright © 2011-2022 走看看