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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值