1.15 定義一個Rectangle類,該類提供getLength和getWidth方法酬凳。利用圖1-18中的findMax例程編寫 一種main方法惠况,該方法創(chuàng)建一個Rectangle數(shù)組并首先找出依面積最大的Rectangle對象,然后 找出依周長最大的Rectangle對象宁仔。
import java.util.Comparator;
public class Rectangle {
private int length;
private int width;
public Rectangle(int length,int width) {
this.length = length;
this.width = width;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getArea() {
return length * width;
}
public int getAllLength() {
return length +width;
}
public String getName(){
return "("+width+","+length+")";
}
public static <AnyType> AnyType findMax(AnyType[] arr, Comparator<AnyType> cmp) {
int maxIndex =0;
for (int i=1;i<arr.length;i++) {
if (cmp.compare(arr[i],arr[maxIndex])>0){
maxIndex = I;
}
}
return arr[maxIndex];
}
public static class MyComparatorArea implements Comparator<Rectangle>{
@Override
public int compare(Rectangle o1, Rectangle o2) {
return o1.getArea()-o2.getArea();
}
}
public static class MyComparatorLength implements Comparator<Rectangle> {
@Override
public int compare(Rectangle o1, Rectangle o2) {
return o1.getAllLength()-o2.getAllLength();
}
}
public static void main(String[] args) {
Rectangle rectangle =new Rectangle(3,4);
Rectangle rectangle2 =new Rectangle(4,4);
Rectangle rectangle3 =new Rectangle(5,2);
Rectangle[] temp = new Rectangle[] {rectangle,rectangle2,rectangle3};
System.out.println(findMax(temp,new MyComparatorArea()).getName());
System.out.println(findMax(temp,new MyComparatorLength()).getName());
}
}
image.png