public class Arrays_ {
public static void main(String[] args) {
int[] arr = {-1, 55, 30, -266, 39, -9999};
//T.bubble(arr);
//这里的 new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// int n1 = (Integer)o1;
// int n2 = (Integer)o2;
// return n2 - n1;
// }
// }
// 匿名内部类其实相当于传给了T类中的bubble01中的接口形参即
// Comparator c = new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// int n1 = (Integer)o1;
// int n2 = (Integer)o2;
// return n2 - n1;
// }
// }
// 编译类型是 Comparator ,运行类型则是匿名内部类,即相当于子类重写父类的方法,发生动态绑定,调方法看运行类型
// 所以运行的是匿名内部类中的compare方法,而不是Comparator接口中的方法
T.bubble01(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
int n1 = (Integer) o1;
int n2 = (Integer) o2;
return n2 - n1;
}
});
System.out.println("======");
System.out.println(Arrays.toString(arr));
}
}
//冒泡排序
class T {
public static void bubble(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void bubble01(int[] arr, Comparator c) {
int temp = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
//数组排序由c.compare(arr[j], arr[j + 1])返回值决定
if (c.compare(arr[j], arr[j + 1]) > 0) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}