package a;
import java.util.Arrays;
public class HelloWorld implements Comparable<HelloWorld> { // 实现Comparable接口,否则会报错
int a;
public HelloWorld(int a) {
this.a=a;
}
@Override
public int compareTo(HelloWorld o) {
if(a>o.a){
return 1;
}
else if (a<o.a){
return -1;
}
return 0;
}
public static void main(String[] args) {
HelloWorld a = new HelloWorld(10);
HelloWorld b = new HelloWorld(90);
HelloWorld c = new HelloWorld(20);
HelloWorld w = new HelloWorld(80);
HelloWorld[] obj = new HelloWorld[4];
obj[0] = a;
obj[1] = b;
obj[2] = c;
obj[3] = w;
for (HelloWorld d : obj
) {
System.out.println(d.a);
}
Arrays.sort(obj);
for (HelloWorld d : obj
) {
System.out.println(d.a);
}
}}
打印结果:
开始前
10
90
20
80
排序后
10
20
80
90