Compare和Comparator
Compare接口和Comparator接口都是用来对自定义Class比较大小的。在需要对自定义类的对象进行排序或者使用TreeSet或TreeMap时,都需要实现Compare接口或者Comparator接口。
下表展示了常见的基本类的自然排序。(虽然一些类共享同一种自然排序,但只有相互可比的类才能排序)
类 | 排序方式 |
---|---|
BigDecimal,BigInteger,Byte,DoubleFloat,Integer,Long,Short | 数字大小 |
Character | Unicode 值的数字大小 |
String | 字符串中字符 Unicode 值 |
##Compare接口 **java.lang. Comparable 接口定义类的自然顺序,实现该接口的类就可以按这种方式排序。**
例如以下定义Point类,并以先x轴后y轴的顺序定义自然顺序:
class Point implements Comparable<Object>{
int x, y;
public Point(){}
public Point(int a, int b)
{
this.x = a;
this.y = b;
}
public int compareTo(Object arg0) {
Point O = (Point)arg0;
if(x == O.x && y == O.y)return 0;
if(x == O.x) return x < O.x ? 1 : -1;
return y < O.y ? 1 : -1;
}
}
然后,就可以以这种自然序对Point类进行排序。
public class Main {
public static void main(String[] args) {
//数组排序
Point p[] = {new Point(2,3), new Point(2,1), new Point(1,2)};
Arrays.sort(p);
for(Point pt : p)
System.out.println("(" + pt.x + "," + pt.y + ")");
System.out.println("================================");
//TreeSet
TreeSet<Point> ts = new TreeSet<Point>();
ts.add(p[2]);
ts.add(p[1]);
ts.add(p[0]);
for(Point pt : ts)
System.out.println("(" + pt.x + "," + pt.y + ")");
}
}
输出
(1,2)
(2,1)
(2,3)
================================
(1,2)
(2,1)
(2,3)
##Comparator接口 >**和Compare接口不同,Comparator接口并不由待排序的类实现,而是由另一个类实现,而在对该类的对象排序或使用TreeSet、TreeMap时将实现类的对象作为参数传递。**
我们还以上面的Point类来示例
package com.test.comp;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;
class Point implements Comparable<Object>{
int x, y;
public Point(){}
public Point(int a, int b)
{
this.x = a;
this.y = b;
}
public int compareTo(Object arg0) {
Point O = (Point)arg0;
if(x == O.x && y == O.y)return 0;
if(x == O.x) return x < O.x ? 1 : -1;
return y < O.y ? 1 : -1;
}
}
class PointComparator implements Comparator<Point>
{
@Override
public int compare(Point o1, Point o2) {
if(o1.x == o2.x && o1.y == o2.y)return 0;
if(o1.x == o2.x) return o1.x < o2.x ? 1 : -1;
return o1.y < o2.y ? 1 : -1;
}
}
public class Main {
public static void main(String[] args) {
//数组排序
Point p[] = {new Point(2,3), new Point(2,1), new Point(1,2)};
Arrays.sort(p, new PointComparator());
for(Point pt : p)
System.out.println("(" + pt.x + "," + pt.y + ")");
System.out.println("================================");
//TreeSet
TreeSet<Point> ts = new TreeSet<Point>(new PointComparator());
ts.add(p[2]);
ts.add(p[1]);
ts.add(p[0]);
for(Point pt : ts)
System.out.println("(" + pt.x + "," + pt.y + ")");
}
}