简单类型数组排序
- Arrays.sort(数组名)默认升序排列
- Arrays.sort(数组名,起始地址,结束地址)
- 倘若改变排列方式,需要重写compare 方法
- 并且需要将其转换为Integer(int 的包装类)类型
int [] array = new int[] {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
Arrays.sort(array);
for(int x : array)
System.out.println(x);
改变默认排序方式
Integer[] arrays = new Integer[m];
for(int i = 0; i < m; i++) {
arrays[i] = sc.nextInt();
}
Arrays.sort(arrays, new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
if(o1 < o2) return -1;
else return 1;
}
});
for(int x : arrays)
System.out.print(x + " ");
复杂类型数组(类数组)排序
- 需要重写Comparator接口提供的方法
- 通过匿名内部类和普通类重写
- 不同的重写方法,sort 参数内容不同
Arrays.sort(array, new Comparator<Sortway_1>(){
@Override
public int compare(Sortway_1 o1, Sortway_1 o2) {
if(o2.score > o1.score) return 1;
else return -1;
}
});
class Compare implements Comparator <Sortway_2>{
@Override
public int compare(Sortway_2 o1, Sortway_2 o2) {
if(o2.score > o1.score) return -1;
else return 1;
}
}
Arrays.sort(array, new Compare());
完整代码
import java.util.Arrays;
import java.util.Comparator;
public class Sort_1 {
public String number;
public int score;
public Sort_1(String number, int score) {
this.number = number;
this.score = score;
}
public static void main(String[] args) {
Sort_1 [] array = {new Sort_1("22170001", 99),
new Sort_1("22170002", 100),
new Sort_1("22170003", 98),
new Sort_1("22170024", 88),
new Sort_1("22170027", 95),
};
Arrays.sort(array, new Comparator<Sort_1>(){
@Override
public int compare(Sort_1 o1, Sort_1 o2) {
if(o2.score > o1.score) return 1;
else return -1;
}
});
for(Sort_1 s : array)
System.out.println(s.number + " " + s.score);
}
}
通过匿名内部类创建要更直观简单一些
import java.util.Arrays;
import java.util.Comparator;
class Compare implements Comparator <Sort_2>{
@Override
public int compare(Sort_2 o1, Sort_2 o2) {
if(o2.score > o1.score) return -1;
else return 1;
}
}
public class Sort_2 {
public String number;
public int score;
public Sort_2(String number, int score) {
this.number = number;
this.score = score;
}
public static void main(String[] args) {
Sort_2 [] array = { new Sort_2("22170001", 99),
new Sort_2("22170002", 100),
new Sort_2("22170003", 98),
new Sort_2("22170024", 88),
new Sort_2("22170027", 95),
};
Arrays.sort(array, new Compare());
for(Sort_2 s : array)
System.out.println(s.number + " " + s.score);
}
}