1、 正常数组排序
1.1自然排序
public static void main(String[] args) {
int a[] = new int[]{1,6,3,0,19};
Arrays.sort(a);//默认的从小到大排序
for (int i : a) {
System.out.println(i);
}
}
1.2倒序(不适用for循环)
public class FullConstructors {
public static void main(String[] args) {
Integer []a = new Integer[]{12,31,4,7,10,20};
Arrays.sort(a);
Collections.reverse(Arrays.asList(a));
System.out.println(Arrays.toString(a));
}
}
2、 类数组排序
package com.online.three;
public class AAA implements Comparable{
int age;
String name;
AAA(){
}
public AAA(int age,String name) {
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;
}
@Override
public int compareTo(Object o) {
AAA obj = (AAA)o;
if(this.age > obj.age) {//从大到小输出
return -1;
} else {
return 1;
}
}
}
package com.online.three;
import java.util.Arrays;
public class Array{
public static void main(String[] args){
AAA []a = {
new AAA(6,"tom6"),
new AAA(6,"tot6"),
new AAA(11,"tom11"),
new AAA(9,"tom9"),
new AAA(0,"tom0")
};
Arrays.sort(a);
for (AAA aaa : a) {
System.out.println(aaa.getName());
}
}
}