Java中Comparable与Comparator的区别

 

/*
 *java中Comparable & Comparator都是用来实现集合中元素的比较,用来进行排序
 *区别:Comparable是集合中内部定义的方法实现的排序,
 *	   Comparator是外部定义的排序方法,
 *想要实现排序,就要在集合外定义Comparator接口的方法或在集合内实现Comparable接口的方法
 *Comparator位于java.util下
 *Comparable位于java.lang下
 * 
 */
//方法一:
@SuppressWarnings("all")
public class TestCompareTo {
	public static void main(String[] args) {
		Circle[] cir = new Circle[4];
		for (int i = 0; i < cir.length; ++i) {
			cir[i] = new Circle(Math.random() * 9 + 1);
		}
		
		Arrays.sort(cir,new Comparator() {
			@Override
			public int compare(Object o1, Object o2) {
				Circle c1 = (Circle) o1;
				Circle c2 = (Circle) o2;
				if(c1.getRadius()> c2.getRadius()){
					return 1;
				}else if(c1.getRadius()< c2.getRadius()){
					return -1;
				}
				return 0;
			}});
		for (Circle circle : cir) {
			System.out.println(circle);
		}
	}
}

class Circle {
	private double radius;

	public Circle() {
		super();
	}

	public Circle(double radius) {
		super();
		this.radius = radius;
	}

	public double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}

	@Override
	public String toString() {
		return "Circle [radius=" + radius + "]";
	}

}

//方法二:
@SuppressWarnings("all")
public class TestCompareTo2{
	public static void main(String[] args) {
		Rectangle[] rec = new Rectangle[3];
		for(int i=0; i<rec.length; ++i){
			rec[i] = new Rectangle(10-i, 8-i);
			
		}
		Arrays.sort(rec);
		for (Rectangle rectangle : rec) {
			System.out.println(rectangle);
		}
	}

}

class Rectangle implements Comparable{
	private int height;
	private int width;
	public Rectangle(int height, int width) {
		super();
		this.height = height;
		this.width = width;
	}
	private int getArea(){
		return height* width;
	}
	@Override
	public String toString() {
		return "Rectangle [height=" + height + ", width=" + width + "]";
	}

	@Override
	public int compareTo(Object o) {
		Rectangle other = (Rectangle) o;
		if(this.getArea()> other.getArea()){
			return 1;
		}else if(this.getArea() < other.getArea()){
			return -1;
		}
		return 0;
	}
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值