自定义对象排序(数组/ArrayList)
当数组或ArrayList的元素为自定义类时,只要该类实现了Comparable接口,就可以进行排序。
以下面的自定义类MyClass为例:
class MyClass implements Comparable {
private String name="";
private int value = 0;
public MyClass() {
}
public MyClass(int value,String name) {
this.value = value;
this.name=name;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int compareTo(Object o) {
MyClass tgt = (MyClass)o;
return ( this.value < tgt.getValue() ? -1 : ( this.value == tgt.getValue() ? 0 : 1));
}
};
private String name="";
private int value = 0;
public MyClass() {
}
public MyClass(int value,String name) {
this.value = value;
this.name=name;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int compareTo(Object o) {
MyClass tgt = (MyClass)o;
return ( this.value < tgt.getValue() ? -1 : ( this.value == tgt.getValue() ? 0 : 1));
}
};
若以数组的方式进行排序,方法如下:
MyClass[] test = new MyClass[5];
test[0] = new MyClass(5,"five");
test[1] = new MyClass(2,"two");
test[2] = new MyClass(3,"three");
test[3] = new MyClass(1,"one");
test[4] = new MyClass(4,"four");
java.util.Arrays.sort(test); //Sort进行的是升序排列,打印test的结果为1,2,3,4,5
test[0] = new MyClass(5,"five");
test[1] = new MyClass(2,"two");
test[2] = new MyClass(3,"three");
test[3] = new MyClass(1,"one");
test[4] = new MyClass(4,"four");
java.util.Arrays.sort(test); //Sort进行的是升序排列,打印test的结果为1,2,3,4,5
若以ArrayList的方式进行排序,方法如下:
ArrayList test= new ArrayList();
for(int i=1; i<=5; i++){
test.add(new MyClass(i,"Name"));
}
Collections.sort(test); //Sort进行的是升序排列,打印test的结果为1,2,3,4,5
Collections.reverse(test); //Sort进行的是降序排列,打印test的结果为5,4,3,2,1
for(int i=1; i<=5; i++){
test.add(new MyClass(i,"Name"));
}
Collections.sort(test); //Sort进行的是升序排列,打印test的结果为1,2,3,4,5
Collections.reverse(test); //Sort进行的是降序排列,打印test的结果为5,4,3,2,1