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

来源:互联网 发布:查找重复删除知乎 编辑:程序博客网 时间:2024/06/05 15:34
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; }@Overridepublic 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> {@Overridepublic int compare(Rectangle o1, Rectangle o2) {// TODO Auto-generated method stubif (o1.getLength() == o2.getLength()) return 0;else if (o1.getLength() > o2.getLength()) return 1;else return -1;}}static class AreaComparator implements Comparator<Rectangle> {@Overridepublic int compare(Rectangle o1, Rectangle o2) {// TODO Auto-generated method stubif (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()));}}

0 0
原创粉丝点击