7-6 学生列表2 (25 分)
编写学生类,包含学号no、姓名name、成绩score,提供必要的构造函数、toString函数和equals/hashcode函数,其中,toString函数的格式为“no:xxx name:xxx score:xxx”,no参与equals和hashcode的计算 在main函数中构造一个容器存放学生对象 从命令行输入多个学生对象,存入列表中 从命令行中读入在列表对象上的操作,具体操作包含: add 添加一个学生(包含学号和学生姓名) delete 删除一个学生(包含学号) set 修改一个学生信息(只修改某学号学生的成绩) 完成操作后按学生的学号从小到大的顺序输出集合中的学生
输入格式:
学生个数 学生对象数据 操作数 操作内容
输出格式:
列表顺序输出集合中的学生
输入样例:
在这里给出一组输入。例如:
4
1 wong 90
2 liu 80
3 chen 70
4 fang 60
3
add 5 duan 80
delete 3
set 4 70
输出样例:
在这里给出相应的输出。例如:
no:1 name:wong score:90
no:2 name:liu score:80
no:4 name:fang score:70
no:5 name:duan score:80
本题有两个需要注意的地方:
1: 从命令行中读入在列表对象上的操作,具体操作包含: add 添加一个学生(包含学号和学生姓名) delete 删除一个学生(包含学号) set 修改一个学生信息(只修改某学号学生的成绩)
从命令行中读取操作,此种方法第一次遇到,解决方法:定义一个字符串,然后用Scanner读取接下来输出的字符,用equals方法进行判断,如果相等,那么就执行相应的方法
String msg = sc.next();
if(msg.equals("add")){
int no = sc.nextInt();
String name = sc.next();
int score = sc.nextInt();
Student stu = new Student(no,name,score);
list.add(stu);
}else if(msg.equals("delete")){
int no = sc.nextInt();
for(j=0;j<list.size(); j++)
if (list.get(j).getNo()==no)
list.remove(j);
}else if(msg.equals("set")){
int no = sc.nextInt();
int score = sc.nextInt();
for(Student stu:list)
if(stu.no == no)
stu.setScore(score);
}
2:完成操作后按学生的学号从小到大的顺序输出集合中的学生
这次的操作需要明白一点:如果要对一个容器进行Collections.sort的排序,而这个容器的泛型并不是传统的数据类型(类似Interger,String),没有compareto方法
如同此题中的Student根据学号排序,那么我们就需要自定义排序
自定义排序:实现Comparator<>接口,重写其中的compare方法
在sort(list,new Comparator<>)如此定义参数即可实现自定义排序,适用场景较多,非常重要
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student t1, Student t2) {
if(t1.getNo()<t2.getNo())
return -1;
else if(t1.getNo()==t2.getNo())
return 0;
else
return 1;
}
});
关于Comparable和Comparator区别比较
Comparable是排序接口,若一个类实现了Comparable接口,就意味着“该类支持排序”。而Comparator是比较器,我们若需要控制某个类的次序,可以建立一个“该类的比较器”来进行排序。
Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”。
两种方法各有优劣, 用Comparable 简单, 只要实现Comparable 接口的对象直接就成为一个可以比较的对象,但是需要修改源代码。 用Comparator 的好处是不需要修改源代码, 而是另外实现一个比较器, 当某个自定义的对象需要作比较的时候,把比较器和对象一起传递过去就可以比大小了, 并且在Comparator 里面用户可以自己实现复杂的可以通用的逻辑,使其可以匹配一些比较简单的对象,那样就可以节省很多重复劳动了。
实质上,Comparable接口中只有唯一一个方法,即compareTo方法,引用 Collections.sort(l1);排序时就是调用的compareTo方法
本体也可以通过实现Comparable接口,实现compareto方法来进行sort的排序,并且直接sort(list)即可
代码如下
通过Student类实现Comparable接口,重写compareto方法,直接调用sort(list)方法即可实现要求
package unsafe1;
import java.util.Scanner;
import java.util.*;
public class Main{
public static void main(String[] args){
ArrayList<Student> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int i,j;
for(i=0; i<k; i++){
int no = sc.nextInt();
String name = sc.next();
int score = sc.nextInt();
Student stu = new Student(no,name,score);
list.add(stu);
}
k = sc.nextInt();
for(i=0; i<k; i++){
String msg = sc.next();
if(msg.equals("add")){
int no = sc.nextInt();
String name = sc.next();
int score = sc.nextInt();
Student stu =