请修改以下代码:package ch15.sort; import java.util.*; class Student implements Comparable{ int height=0; int weight; String name; Student(String n,int h,int w) { name=n; height = h; weight = w; } public int compareTo(Student st) { //两个Student对象大小关系 return (this.height-st.height); } } public class Example15_4_1 { public static void main(String args[ ]) { List list = new LinkedList(); list.add(new Student("张三",188,86)); list.add(new Student("李四",178,83)); list.add(new Student("赵大龙",198,84)); list.add(new Student("李云龙",175,80)); Iterator iter=list.iterator(); System.out.println("排序前,链表中的数据:"); while(iter.hasNext()){ Student stu=iter.next(); System.out.println(stu.name+ "身高:"+stu.height+"体重:"+stu.weight); } Collections.sort(list); System.out.println("排序后,链表中的数据:"); iter=list.iterator(); while(iter.hasNext()){ Student stu=iter.next(); System.out.println(stu.name+ "身高:"+stu.height+"体重:"+stu.weight); } } }具体要求如下:(1)两个学生比较大小结果与他们名字字符串的比较结果一致(2)有时需要按身高来排,若身高相同则按体重排序
时间: 2024-03-07 17:50:39 浏览: 192
修改后的代码如下:
```java
package ch15.sort;
import java.util.*;
class Student implements Comparable<Student> {
int height = 0;
int weight;
String name;
Student(String n, int h, int w) {
name = n;
height = h;
weight = w;
}
public int compareTo(Student st) {
// 先比较身高
int cmp = this.height - st.height;
if (cmp == 0) {
// 如果身高相同,则比较体重
cmp = this.weight - st.weight;
}
// 如果身高和体重都相同,则按名字字符串比较
if (cmp == 0) {
cmp = this.name.compareTo(st.name);
}
return cmp;
}
}
public class Example15_4_1 {
public static void main(String args[]) {
List<Student> list = new LinkedList<Student>();
list.add(new Student("张三", 188, 86));
list.add(new Student("李四", 178, 83));
list.add(new Student("赵大龙", 198, 84));
list.add(new Student("李云龙", 175, 80));
Iterator<Student> iter = list.iterator();
System.out.println("排序前,链表中的数据:");
while (iter.hasNext()) {
Student stu = iter.next();
System.out.println(stu.name + "身高:" + stu.height + "体重:" + stu.weight);
}
Collections.sort(list);
System.out.println("排序后,链表中的数据:");
iter = list.iterator();
while (iter.hasNext()) {
Student stu = iter.next();
System.out.println(stu.name + "身高:" + stu.height + "体重:" + stu.weight);
}
}
}
```
修改后的代码满足以下要求:
1. 两个学生比较大小结果与他们名字字符串的比较结果一致。
2. 有时需要按身高来排,若身高相同则按体重排序。
阅读全文