编写Student类,
要求该类通过实现系统的泛型接口Comparable<E>接口规定该类的对象的大小关系,
学生按其身高(height)值确定之间的大小关系。
创建链表LinkedList,在链表中添加多个Student对象,
通过Collections调用sort方法将链表中的对象按身其height值升序排序后输出所有学生。
例如,对list进行排序: Collections.sort(list);
输入格式:
先输入学生数量:3,然后输入每个学生的姓名和身高,如输入样例所示。
输入样例:
3
张三 188
李四 178
周五 198
结尾无空行
输出格式:
按身高升序输出所有学生,如输出样例所示。
输出样例:
排序后:
李四 178
张三 188
周五 198
结尾无空行
此题有两种解法:
解法1:Student类为Comparable接口的实现类(一种内部比较的方法)
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
LinkedList<Student> list = new LinkedList<>();//泛型链表
for (int i = 0; i < num; i++){
Student s = new Student(sc.next(),sc.nextInt());
list.add(s);//构造链表,添加元素
}
Collections.sort(list);//实现内部排序
System.out.println("排序后:");
for (int i = 0; i < list.size(); i++){
Student s = list.get(i);
System.out.println(s.name+" "+s.height);
}
}
}
class Student implements Comparable<Student>{
String name;
int height;
Student(){}
Student(String name,int height){
this.name = name;
this.height = height;
}
public int compareTo(Student s){//重写Comparable的compareTo方法
return this.height-s.height;
}
}
解法2:Student类为comparator的实现类(一种外部比较(另外生成比较器)的方法)
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
LinkedList<Student> list = new LinkedList<>();
for (int i = 0; i < num; i++){
Student s = new Student(sc.next(),sc.nextInt());
list.add(s);
}
Collections.sort(list,new Student());//注意sort方法的形参变为了链表对象和实现了comparator接口的对象
for (int i = 0; i < list.size(); i++){
Student s = list.get(i);
System.out.println(s.name+" "+s.height);
}
}
}
import java.util.Comparator;
public class Student implements Comparator<Student> {
String name;
int height;
Student(){}
public Student(String name, int height) {
this.height = height;
this.name = name;
}
public int compare(Student s1,Student s2){//重写comparator接口的compare方法
if (s1.height>s2.height){
return 1;
}
else if (s1.height<s2.height){
return -1;
}
else {
return 0;
}
}
}
本题根据题目要求的话,应该使用方法1,实现Comparable接口,但是这两种代码都可以做出来。
Comparable接口是排序接口,类实现了Comparable接口,就表明了该类支持排序,
而Comparator接口是比较器接口,是建立一个类的比较器来排序的;
注意Comparable接口是重写comparaTo方法,而Comparator接口是重写compare方法。