Student类中有name和age属性,在List<Student>里存了几个Student对象,要求按照学生年龄的降序输出。请高手帮忙~
解决方案 »
- 求助:关于与系统剪贴板交互的程序
- 我写的描述两个字符串相似程度的算法
- 那里有错了,请指点,谢谢!
- java 中实现象象vb中的doevents功能怎么解决(在线等待)
- 难道是那些书教错了
- Java第一步:Hello World 问题
- 请问:如果名字是中文的文件来压缩,则压缩包中的文件名字变成乱码,如何解决带中文名字压缩的问题?
- Arrays.sort(),collectins.sort()这些排序的方法好像是大小写区分的。大写在前,小写在后。如何大小写不区分排序。
- 请教一个关于weblogic5.1+SunOS5.7的问题???
- 希望了解java,能推荐一个好的开发工具和一本好的入门书籍吗?我以前直到现在都在用VC,接下来想在C#和java中选一个做为第二语言。
- 几个小问题,挺有意思的,请来看看。
- java 中字符串 怎么比较大小
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;public class ListSort {
private void sortByType(List<Student> list) {
Collections.sort(list, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
return o1.getAge()>o2.getAge()?1:0;
}
});
} public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student student1 = new Student(23, "小明");
Student student2 = new Student(12, "小刘");
Student student3 = new Student(7, "小张");
list.add(student1);
list.add(student2);
list.add(student3);
ListSort listSort = new ListSort();
listSort.sortByType(list);
for(Student student : list) {
System.out.println(student.getAge()+"\t"+student.getName());
}
} public static class Student {
int age;
String name;
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
}
so quickly!!package test;import java.util.Arrays;public class Student implements Comparable<Student>{ private String name; private int age; public Student(String name,int age){
this.age = age;
this.name = name;
}
public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int compareTo(Student o) {
// TODO Auto-generated method stub
if(this.age>o.age)
return -1;
else if(this.age<o.age)
return 1;
else
return 0;
}
public String toString(){
return "name:"+name+",age:"+age;
}
public static void main(String[] args) {
Student [] sts = new Student[5];
sts[0] = new Student("aaaa",13);
sts[1] = new Student("bbbb",18);
sts[2] = new Student("cccc",68);
sts[3] = new Student("dddd",2);
sts[4] = new Student("eeee",5);
Arrays.sort(sts);
for(Student s:sts)
System.out.println(s);
}}