1.15 定义一个Rectangle类,该类提供getLength和getWidth方法。利用图1-18中的findMax例程编写 一种main方法,该方法创建一个Rectangle数组并首先找出依面积最大的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
网友评论