有时候需要对Collection或者不为单一数字的Array进行比较,有两种方法,1是实现Comparable接口,2是实现Comparator接口。
1.ComParable接口
Comparable接口的定义如下:
public interface Comparable<T>
{
public int compareTo(T o);
}
此方法返回一个int类型的数据,但是此int的值只能是一下三种:
1:表示大于
-1:表示小于
0:表示相等
实例:
package zy.java.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ComparableTest implements Comparable<ComparableTest> { private String id; private int age; public ComparableTest(String id,int age) { this.id = id; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(ComparableTest c) { return this.age - c.getAge(); } public static void main(String[] args) { //Collection ComparableTest ct1 = new ComparableTest("a",39); ComparableTest ct2 = new ComparableTest("b",31); ComparableTest ct3 = new ComparableTest("c",38); List<ComparableTest> list = new ArrayList<ComparableTest>(); list.add(ct1); list.add(ct2); list.add(ct3); Collections.sort(list); for(int i=0;i<list.size();i++) { System.out.println(list.get(i).getId()); } System.out.println("-------------------------------------------"); //Array ComparableTest[] ct = new ComparableTest[]{ new ComparableTest("a",39), new ComparableTest("b",31), new ComparableTest("c",38) }; Arrays.sort(ct); for(int i=0;i<ct.length;i++) { System.out.println(ct[i].getId()); } } }