对象数组排序
A数组类
public class A implements Comparable{
int age;
int i;
public A(int i,int age) {
super();
this.age = age;
this.i = i;
}
@Override
public String toString() {
return "A [age=" + age + ", i=" + i + "]";
}
public int compareTo(Object o) {
A a = (A)o;
//升序
//return this.age-a.age;
//降序
//return a.age-this.age;
/*先按年龄排序,再按i排序*/
int rs = this.age-a.age;
if(rs!=0){
return rs;
}
//升序
//return this.i-a.i;
//降序
return a.i - this.i;
}
}
Test类
import java.util.Arrays;
import java.util.Random;
public class Test {
public static void main(String[] args) {
A[]arr = new A[4];
initArr(arr);
System.out.println("排序前:"+Arrays.toString(arr));
Arrays.sort(arr);
System.out.println("排序前:"+Arrays.toString(arr));
}
static void initArr(A[]arr){
Random r = new Random();
for(int i = 0;i<arr.length;i++){
arr[i] = new A(i,r.nextInt(10));
}
}
}