Comparable:
使用此接口需要重寫commpareTo函數。
格式:public int compareTo(Object o)
Comparetor:
可以單獨創建一個比較器類,也可創建爲內部類。
比較器類實現 Comparator接口,重寫compare。
格式: public int compare(Object o1,Object o2)
實例:
1.抽象類和子類圖形類
抽象類
package Geometric;
abstract class GeometricObject
{
public abstract double getPerimeter();//周長
public abstract double getArea();//面積
}
矩形
package Geometric;
public class Rectangle extends GeometricObject implements Comparable
{
public double length = 0.00;//長度
public double width = 0.00;//寬度
public Rectangle(double length,double width)
{
this.length = length;
this.width = width;
}
public double getPerimeter()
{
return (this.length+this.width)*2;
}
public double getArea()
{
return this.length * this.width;
}
public int compareTo(Object o)
{
if(getArea()>((Rectangle)o).getArea())
return 1;
else if (getArea()==((Rectangle)o).getArea())
return 0;
else
return -1;
}
public String toString()
{
return "矩形面積:"+getArea();
}
}
圓形
package Geometric;
public class Circle extends GeometricObject
{
public double radius = 0.00;//半徑
public Circle(double radius)
{
this.radius = radius;
}
public double getPerimeter()
{
return 2*3.14*this.radius;
}
public double getArea()
{
return 3.14 * this.radius *this.radius;
}
public String toString()
{
return "圓形面積:"+getArea();
}
}
2.面積比較器類
class AreaComparator implements Comparator<Geo>
{
public int compare(Geo o1,Geo o2)
{
double a = o1.getArea();
double b = o2.getArea();
return (a>b?1:(a==b?0:-1));
}
}
3.測試類
package Geometric;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class ComparatorTest
{
public static void main(String[] args)
{
//測試Comparable接口
Rectangle re1= new Rectangle(3,8);
Rectangle re2= new Rectangle(50,1);
System.out.println(re1.compareTo(re2));
System.out.println("******************");
//測試Comparator比較器
GeometricObject r1 = new Rectangle(1,2);
GeometricObject r2 = new Rectangle(4,20);
GeometricObject c1 = new Circle(4);
List<GeometricObject> list = new ArrayList<GeometricObject>();
list.add(r1);
list.add(r2);
list.add(c1);
areaComparator myComparator = new areaComparator();
Collections.sort(list,myComparator);
for(GeometricObject p : list){
System.out.println(p.toString());
}
}
}
4.運行結果