编写学生类,该类定义了3个属性:学号,姓名,成绩。可以通过构造方法设置3个属性的内容,并覆写Object类中的toString()方法,在List集合中加入5个学生对象,并将内容输出,之后使用比较器将

编写学生类,该类定义了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]);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值