java数组排序

定义数组可以这样,比如int a[] = new int[10];

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.Arrays;
import java.util.Comparator;
class Dog{
int size;
public Dog(int s){
size = s;
}
}

class DogSizeComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
return o1.size - o2.size;
}
}

public class ArraySort {

public static void main(String[] args) {
Dog d1 = new Dog(2);
Dog d2 = new Dog(1);
Dog d3 = new Dog(3);

Dog[] dogArray = {d1, d2, d3};
printDogs(dogArray);

Arrays.sort(dogArray, new DogSizeComparator());
printDogs(dogArray);
}

public static void printDogs(Dog[] dogs){
for(Dog d: dogs)
System.out.print(d.size + " " );

System.out.println();
}
}