Comparable和Comparetor的使用方法

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.运行结果
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章