转自:http://www.2cto.com/kf/201305/210466.html
compareTo就是比较两个值,如果前者大于后者,返回1,等于返回0,小于返回-1,我下面给出了例子,由于比较的变量我用的是int,int型可以直接比较,所有没有用到compareTo比较,如果声明的是Date、String、Integer或者其他的,可以直接使用compareTo比较,
public int compareTo(TestModel1 o) {
return this.str1.compareTo(o.str1);
}
compareTo方法内必须做非空判断(规范问题),当然int类型就不用了。
注意事项:
1模型必须实现Comparable<T>接口
2Collections.sort(list);会自动调用compareTo,如果没有这句,list是不会排序的,也不会调用compareTo方法
3如果是数组则用的是Arrays.sort(a)方法
代码如下:
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<TestModel1> list = new ArrayList<TestModel1>();
list.add(new TestModel1(1,"",""));
list.add(new TestModel1(3,"",""));
list.add(new TestModel1(2,"",""));
list.add(new TestModel1(6,"",""));
list.add(new TestModel1(9,"",""));
list.add(new TestModel1(7,"",""));
System.out.print("排序前:");
for (TestModel1 t : list) {
System.out.print(t.getInteger()+" ");
}
Collections.sort(list);//自动调用compareTo
System.out.print("
排序后:");
for (TestModel1 t : list) {
System.out.print(t.getInteger()+" ");
}
}
}
package test;
public class TestModel1 implements Comparable<TestModel1>{
private int integer;
private String str1;
private String str2;
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
public String getStr2() {
return str2;
}
public void setStr2(String str2) {
this.str2 = str2;
}
public TestModel1(Integer integer, String str1, String str2) {
super();
this.integer = integer;
this.str1 = str1;
this.str2 = str2;
}
public int compareTo(TestModel1 o) {
if(this.integer<o.integer)return -1;
else if(this.integer==o.integer)return 0;
else return 1;
}
}
效果如下: