java_Comparable比较对象
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);
}
}
} Student<Student> stu1=new Student<Student>("张三",18,2000d);
使用了Comparable类的泛型,并
class Student implements Comparable<Student>,为什么实例化对象时,不需要如上第一行这样写,写了反而报错???????????{:10_261:}
页:
[1]