鱼C论坛

 找回密码
 立即注册
查看: 2498|回复: 1

[学习笔记] java_Comparable比较对象

[复制链接]
发表于 2018-9-21 00:29:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import java.util.*;
class Student implements Comparable<Student>
{
        private String name;
        private int age;
        private double mark;
        public Student(){};
        public Student(String name,int age,double mark)
        {
                this.name=name;
                this.age=age;
                this.mark=mark;
        }
        public void setName(String name)
        {
                this.name=name;
        }
        public void setAge(int age)
        {
                this.age=age;
        }
        public void setMark(double mark)
        {
                this.mark=mark;
        }
        public String getName()
        {
                return this.name;
        }
        public int getAge()
        {
                return this.age;
        }
        public double getMark()
        {
                return this.mark;
        }
        public String toString()
        {
                return "姓名==>"+this.name+"  年龄==>"+this.age+"  成绩==>"+this.mark;
        }

        public int compareTo(Student stu)
        {
                if(this.mark>stu.mark)
                {
                        return 1;
                }
                else if(this.mark<stu.mark)
                {
                        return -1;
                }
                else
                {
                        return 0;
                }
        }

}
//****************************************************************************
public class ComparableDemo1
{
        public static void main(String[] args)
        {
                Student stu1=new Student("张三",18,2000d);
                Student stu2=new Student("李四",22,4000d);
                Student stu3=new Student("王五",33,7000d);
                Student[] stu=new Student[]{stu1,stu2,stu3};//组成这个对象的数组,仍然用这个引用类型
                Arrays.sort(stu);
                for(Student x:stu)
                {
                        System.out.println(x);
                }
        }
}
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2018-9-21 00:31:24 | 显示全部楼层
Student<Student> stu1=new Student<Student>("张三",18,2000d);

使用了Comparable类的泛型,并
class Student implements Comparable<Student>,为什么实例化对象时,不需要如上第一行这样写,写了反而报错???????????
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 10:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表