0
点赞
收藏
分享

微信扫一扫

关于尚硅谷JAVA系列课 集合的课后练习题的代码

程序员伟杰 2022-02-12 阅读 68

 class ADD {
        public static void main(String[] args) {
            Set treeSet = new TreeSet();
            treeSet.add(new Student("张",21));
            treeSet.add(new Student("张1",32));
            treeSet.add(new Student("张1",42));
            treeSet.add(new Student("张23",54));
            treeSet.add(new Student("张1321",56));
            treeSet.add(new Student("张1321",76));
            treeSet.add(new Student("张22",64));
            treeSet.add(new Student("张1331",81));
            treeSet.add(new Student("张1231",99));
        //添加元素
            Iterator iterator = treeSet.iterator();
//    使用迭代器遍历
            int i = 3;
            while (i > 0){
                System.out.println(iterator.next());
                i--;
            }
        }

    }
    class Student implements Comparable{
        String name ;//姓名
        Integer mark;//分数

        public Student(String name, int mark) {
            this.name = name;
            this.mark = mark;
        }
        public Student(){}
        @Override

        public int compareTo(Object o) {
            if (o instanceof Student){//判断o是否是Student类的实例
                Student student = (Student) o;//强转
                if (this.mark.compareTo(student.mark) > 0){
                    //上面这个IF语句是返回1的,则代表按升序排
                        return -1;//返回负1则代表按降序排
                    //CompareTo是按照-1,1,0来确定元素之间的大小的。
                }
            }
            return 0;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", mark=" + mark +
                    '}';
        }
    }

运行结果:

 

 

举报

相关推荐

0 条评论