Java集合排序练习3-5,烦请老师检查并指正~

Java集合排序练习3-5,烦请老师检查并指正~

package com.imooc.array.comparator;

public class Student {
private int stuId;
private String name;
private int age;

public Student() {
}

public Student(int stuId, String name, int age) {
this.setStuId(stuId);
this.setName(name);
this.setAge(age);
}

public int getStuId() {
return stuId;
}

public void setStuId(int stuId) {
this.stuId = stuId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Student [stuId=" + stuId + ", name=" + name + ", age=" + age + "]";
}



}

​package com.imooc.array.comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestStudent implements Comparator <Student> {

public static void main(String[] args) {
Student stu1 = new Student(40, "Peter", 20);
Student stu2 = new Student(28, "Angel", 19);
Student stu3 = new Student(35, "Tom", 18);
List <Student> list = new ArrayList <Student> ();
list.add(stu1);
list.add(stu2);
list.add(stu3);
System.out.println("Before:");
for(Student stu: list) {
System.out.println(stu);
}
System.out.println("After:");
Collections.sort(list, new TestStudent());
for(Student stu: list) {
System.out.println(stu);
}



}

@Override
public int compare(Student o1, Student o2) {
String name1 = o1.getName();
String name2 = o2.getName();
int n = name1.compareTo(name2);
return n;
}

}

正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学你好,同学的代码符合题意,书写规范,逻辑清晰,运行结果符合要求,做得很棒。

祝学习愉快~


问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师