package 计算机挑战赛国赛;
import java.util.ArrayList;
import java.util.Collections;
public class test8 {
static class student implements Comparable<student>{
String name;
int age;
student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public int compareTo(student o) {
return this.age-o.age;
}
}
public static void main(String[] args) {
ArrayList<student> list = new ArrayList<student>();
list.add(new student("zhangsan",22));
list.add(new student("husheng",20));
list.add(new student("lisi",25));
Collections.sort(list);
for (student student : list) {
System.out.println(student.name+" "+student.age);
}
}
}
输出:
husheng 20
zhangsan 22
lisi 25
package 计算机挑战赛国赛;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class test8 {
static class student {
String name;
int age;
student(String name,int age){
this.name=name;
this.age=age;
}
}
public static void main(String[] args) {
student[] arr = new student[3];
arr[0]=new student("zhangsan",22);
arr[1]=new student("husheng",20);
arr[2]=new student("lisi",25);
Arrays.sort(arr,0,3,(o1,o2)->o1.age-o2.age);
//如果o1.age或者o2.age为浮点型的话,应改为(int)(o1.age-o2.age),将其转化为整形
//也可以将o1.age和o2.age扩大整数倍,使其变成整数。如(int)(o1.age*100-o2.age*100)
for (student student : arr) {
System.out.println(student.name+" "+student.age);
}
}
}
输出:
husheng 20
zhangsan 22
lisi 25