AP计算机A自学笔记:Comparable接口

Comparable接口用于对象的比较,任何使用Comparable接口的类必须提供compareTo方法。这个方法返回一个整数代表两个对象差值。如果相比较的两个接口类型不可比,会抛出ClassCastException

compareTo应用例子

package inheritanceAndPolymorphism;

import java.util.*;

public abstract class Shape implements Comparable{
   private String name;
   
   
   //constructor
   public Shape(String shapeName) {
	   name = shapeName;
   }
   
   
   public String getName() { //an abstract method can have both abstract and concrete method
	   return name;
   }
   
   
   public abstract double area();
   public abstract double perimeter();
   
   
   public double semiPerimeter() {
	   return perimeter() / 2;
   }
   
   
   public int compareTo(Object obj) {
	   final double EPSILON  = 1.0e-15; //machine precision, in case of round-off error
	   
	   
	   Shape rhs = (Shape) obj;
	   double diff = area() - rhs.area();
	   if (Math.abs(diff) <= EPSILON * Math.abs(area())) {
		   return 0; //area of this shape equals area of obj
	   } else if (diff < 0) {
		   return -1; //area of this shape less than area of obj
	   } else {
		   return 1; //area of this shape greater than area of obj
	   }
   }
   /*
    * The Circle Square, and other subclasses of Shape will automatically implement
    * Comparable and inherit the compareTo method
    */
   
   

注意:
1对于小数的比较,要防止round-off error,因此判断是否相等不可直接等号,而是判断误差是否在计算机精度之内
2compareTo的第一步要把Object转化为该类类型(Shape),否则计算机将找不到方法Area()

下面例子在两个对象中找最大

package inheritanceAndPolymorphism;

public class FindMaxTest {

	//return the larger of two objects a and b
	public static Comparable max (Comparable a, Comparable b) {
		if (a.compareTo(b) > 0) {
			return a;
		} else {
			return b;
		}
	}
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//test max on two Shape objects
		Shape s1 = new Circle(3.0, "circle");
		Shape s2 = new Square(6.5, "square");
		System.out.println("Area of " + s1.getName() + " is " + s1.area());
		System.out.println("Area of " + s2.getName() + " is " + s2.area());
		Shape s3 = (Shape)max(s1, s2);
		System.out.println("The larger shape is the " + s3.getName());
		
	}

}

1本例中方法参数为Comparable类型,s1 s2均为Comparable因此不需要类型转换
2基础数据类型不是对象,不可使用Comparable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值