Java类库中也定义了许多接口,有些接口中没有定义任何方法,这些接口称为标识接口,如java.lang包中定义的Cloneable接口、java.io包中的Serializable接口。有些接口中定义了若干方法,如java.lang包中Comparable接口中定义的comapreTo()方法、AutoClosable接口定义的close()方法、Runnable接口中定义的run()方法。
Comparable接口
要比较两个String对象的大小,可以使用String类的compareTo()方法。现在假设要比较两个Square对象的大小,Square类是用户定义的类,无法比较大小。要想比较Square对象的大小,如按面积比较,需要实现Comparable< T >接口的compareTo()方法。
- Shape抽象类
public abstract class Shape {
String name;
public Shape() {
super();
}
public Shape(String name) {
super();
this.name = name;
}
public abstract double getArea();
public abstract double getPerimeter();
}
- Square类
public class Square extends Shape implements Comparable<Square> {
private double length;
private double width;
public Square() {
this(1, 1);
}
public Square(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() { //面积
return length * width;
}
@Override
public double getPerimeter() { //周长
return 2 * (length + width);
}
@Override
public String toString() {
return "Square [length=" + length + ", width=" + width + "]";
}
@Override
public int compareTo(Square o) { //面积从小到大排序
return (int) (getArea() - o.getArea());
}
}
- TestComparable类
import java.util.Arrays;
public class TestComparable {
public static void main(String[] args) {
Square[] s = { new Square(), new Square(2, 2), new Square(2, 5), new Square(3, 4) };
Arrays.sort(s);
for (Square x : s) {
System.out.print(x + "\t");
}
}
}
- 控制台测试结果
Square [length=1.0, width=1.0] Square [length=2.0, width=2.0] Square [length=2.0, width=5.0] Square [length=3.0, width=4.0]
编程练习
eg:设计一个Position类,该类有x和y两个成员变量表示坐标。要求该类实现Comparable接口的compareTo()方法,实现比较两个Position对象到原点(0,0)的距离之差。
- Position类
public class Position implements Comparable<Position> {
double x;
double y;
public Position() {
super();
}
public Position(double x, double y) {
super();
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double distance() { // 到原点的距离
return Math.sqrt(x * x + y * y);
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public int compareTo(Position arg0) { //距离从小到大排序
return (int) (Math.pow(distance(), 2) - Math.pow(arg0.distance(), 2));
}
}
- TestComparable类
import java.util.Arrays;
public class TestComparable {
public static void main(String[] args) {
Position[] a = { new Position(), new Position(2, 5), new Position(1, 1), new Position(7, 2), new Position(4, 6) };
Arrays.sort(a);
for (Position x : a) {
System.out.print(x + "\t");
}
}
}
- 控制台测试结果
(0.0,0.0) (1.0,1.0) (2.0,5.0) (4.0,6.0) (7.0,2.0)