编写学生类,该类定义了3个属性:学号,姓名,成绩。可以通过构造方法设置3个属性的内容,并覆写Object类中的toString()方法,在List集合中加入5个学生对象,并将内容输出,之后使用比较器将对象的内容进行排序并显示在屏幕上。
import java.util.List;
import java.util.ArrayList;class Student implements Comparable<Student>{
private int number;
private String name;
private float score;
public Student(int number,String name,float score){
this.setNumber(number);
this.setName(name);
this.setScore(score);
}
public String toString(){
return "学号:"+this.number+" 姓名:"+this.name+" 分数:"+this.score;
}
public int compareTo(Student stu){
if(this.number>stu.number){
return -1;
}else if(this.number<stu.number){
return 1;
}else{
if(this.score>stu.score){
return 1;
}else if(this.score>stu.score){
return -1;
}else{
return 0;
}
}
}
public void setNumber(int number){
this.number=number;
}
public int getNumber(){
return this.number;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setScore(float score){
this.score=score;
}
public float getScore(){
return this.score;
}
}
public class StudentDemo{
public static void main(String[] args){
Student stu1=new Student(20080808, "张三", 95);
Student stu2=new Student(20100203, "李四", 99);
Student stu3=new Student(20071010, "王五", 98);
Student stu4=new Student(20080113, "朱六", 93);
Student stu5=new Student(20101030, "赵七", 96);
List<Student> stu=new ArrayList<Student>();
stu.add(stu1);
stu.add(stu2);
stu.add(stu3);
stu.add(stu4);
stu.add(stu5);
System.out.println("比较之前:");
for(int i=0;i<stu.size();i++){
System.out.println(stu.get(i));
}
System.out.println("比较之后:");
Object[] str=stu.toArray();
java.util.Arrays.sort(str);
for(int i=0;i<str.length;i++){
System.out.println(str[i]);
}
}
}