使用Java内置迭代器实现对学生信息的遍历,要求按学生年龄由大到小的次序输出学生信息。
1个回答
展开全部
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 通过实现comparable接口来比较多个对象的属性值,并按顺序输出
* @author young
*
*/
class Teacher implements Comparable<Teacher> {
private String no;
private String name;
private int age;
private String zy;
public Teacher(String no, String name, int age, String zy) {
super();
this.no = no;
this.name = name;
this.age = age;
this.zy = zy;
}
// 三个返回结果都要写出来
public int compareTo(Teacher o) {
if(this.age > o.age){
return -1;
}else if(this.age < o.age){
return 1;
}else {
return 0;
}
}
@Override
public String toString(){
return "姓名: " + this.name + ". 编号: " + this.no + ". 年龄: " + this.age
+ ". 专业: " + this.zy;
}
}
public class ComparableTest1 {
public static void main(String[] args) {
Teacher s1 = new Teacher("291", "张", 50, "音乐专业");
Teacher s2 = new Teacher("423", "李", 30, "计算机专业");
Teacher s3 = new Teacher("21", "王", 29, "机械专业");
Teacher s4 = new Teacher("445", "高", 34, "国贸专业");
List<Teacher> list = new ArrayList<Teacher>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
Collections.sort(list);
System.out.println("按照年龄进行排序输出: ");
for(Teacher stu : list){
System.out.println(stu.toString());
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询