Comparable接口中compareTo用法

compareTo就是比较两个值,如果前者大于后者,返回1,等于返回0,小于返回-1,我下面给出了例子,由于比较的变量我用的是int,int型可以直接比较,所有没有用到compareTo比较,如果声明的是Date、String、Integer或者其他的,可以直接使用compareTo比较,

	public int compareTo(TestModel1 o) {
		return this.str1.compareTo(o.str1);
	}

compateTo方法内必须做非空判断(规范问题),当然int类型就不用了。

注意事项:

        1模型必须实现Comparable接口

        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 list = new ArrayList();
		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("\n排序后:");
		for (TestModel1 t : list) {
			System.out.print(t.getInteger()+" ");
		}
	}
}

package test;

public class TestModel1 implements Comparable{
	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

效果如下:




你可能感兴趣的:(Java)