数据结构与算法分析Java版练习1.15

时间:2023-02-14 13:58:35
package ch01;

import java.util.Comparator;

/**
* 练习1.15 定义一个Rectangle类,该类提供getLength和getWidth方法。利用图1-18中的findMax例程编写
* 一种main方法,该方法创建一个Rectangle数组并首先找出依面积最大的Rectangle对象,然后
* 找出依周长最大的Rectangle对象。
*/
class Rectangle {
private int width, height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getLength() { return (width + height) << 2; }
public int getArea() { return width * height; }
@Override
public String toString() {
return "width:" + width + ", height:" + height;
}
}

public class EX15 {
public static <T>
T findMax(T[] a, Comparator<? super T> cmp) {
int maxIndex = 0;
for (int i = 0; i < a.length; ++i) {
if (cmp.compare(a[i], a[maxIndex]) > 0) {
maxIndex = i;
}
}
return a[maxIndex];
}

static class LengthComparator implements Comparator<Rectangle> {
@Override
public int compare(Rectangle o1, Rectangle o2) {
// TODO Auto-generated method stub
if (o1.getLength() == o2.getLength()) return 0;
else if (o1.getLength() > o2.getLength()) return 1;
else return -1;
}
}

static class AreaComparator implements Comparator<Rectangle> {
@Override
public int compare(Rectangle o1, Rectangle o2) {
// TODO Auto-generated method stub
if (o1.getArea() == o2.getArea()) return 0;
else if (o1.getArea() > o2.getArea()) return 1;
else return -1;
}
}

public static void main(String[] args) {
Rectangle[] a = new Rectangle[] {
new Rectangle(1, 2), new Rectangle(2, 3), new Rectangle(3, 4),
new Rectangle(2, 9), new Rectangle(2, 5), new Rectangle(5, 5),
};
System.out.println(findMax(a, new LengthComparator()));
System.out.println(findMax(a, new AreaComparator()));
}
}