1.15 定义一个Rectangle类,该类提供getLength和getWidth方法
1.15 定义一个Rectangle类,该类提供getLength和getWidth方法。利用图1-18中的findMax例程编写 一种main方法,该方法创建一个Rectangle数组并首先找出依面积最大的Rectangle对象,然后 找出依周长最大的Rectangle对象。
import java.util.Comparator; /** * * @author 疯狂龅牙酥 * */ public class One_fifteen { public static void main(String[] args) { // TODO Auto-generated method stub Rectangle[] recs = new Rectangle[] { new Rectangle(1,2), new Rectangle(1,3), new Rectangle(1,4), new Rectangle(1,5), new Rectangle(1,6)}; System.out.println(findMax(recs, new AreaComparator()).getArea()); System.out.println(findMax(recs, new CircumferenceComparator()).getCircumference()); } public static <AnyType> AnyType findMax(AnyType[] arr, Comparator<? super AnyType> cmp) { int maxIndex = 0; for(int i=1; i<arr.length; i++) { if(cmp.compare(arr[maxIndex], arr[i])<0) { maxIndex = i; } } return arr[maxIndex]; } } class Rectangle{ private int length; private int width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public int getLength() { return this.length; } public int getWidth() { return this.width; } public int getArea() { return this.length * this.width; } public int getCircumference() { return 2 * (this.length + this.width); } } class AreaComparator implements Comparator<Rectangle>{ @Override public int compare(Rectangle o1, Rectangle o2) { // TODO Auto-generated method stub int area1 = o1.getLength() * o1.getWidth(); int area2 = o2.getLength() * o2.getWidth(); if(area1 < area2) { return -1; }else if(area1 > area2) { return 1; }else { return 0; } } } class CircumferenceComparator implements Comparator<Rectangle>{ @Override public int compare(Rectangle o1, Rectangle o2) { int c1 = 2*(o1.getLength() + o1.getWidth()); int c2 = 2*(o2.getLength() + o2.getWidth()); if(c1 < c2) { return -1; }else if(c1 > c2) { return 1; }else { return 0; } } }