【问题标题】:How to write this generic object program?如何编写这个通用目标程序?
【发布时间】:2015-04-10 02:22:41
【问题描述】:

问题:定义一个提供 getLength 和 getWidth 方法的 Rectangle 类。使用 图 1.18 中的 findMax 例程,编写一个 main 创建一个 Rectangle 数组 并先根据面积求最大矩形,再根据周长求最大矩形。

到目前为止,我所做的是在构造函数中创建一个带有参数 width 和 height 的类矩形。之后,我实现了两个 getter 方法,其中实例变量 width 和 height 为它们各自的 getter 方法返回。所以我需要第二部分的帮助。

图 1.18

1 // Generic findMax, with a function object.
2 // Precondition: a.size( ) > 0.
3 public static <AnyType>
4 AnyType findMax( AnyType [ ] arr, Comparator<? super AnyType> cmp )
5 {
6 int maxIndex = 0;
7
8 for( int i = 1; i < arr.size( ); i++ )
9 if( cmp.compare( arr[ i ], arr[ maxIndex ] ) > 0 )
10 maxIndex = i;
11
12 return arr[ maxIndex ];
13 }
14
15 class CaseInsensitiveCompare implements Comparator<String>
16 {
17 public int compare( String lhs, String rhs )
18 { return lhs.compareToIgnoreCase( rhs ); }
19 }
20
21 class TestProgram
22 {
23 public static void main( String [ ] args )
24 {
25 String [ ] arr = { "ZEBRA", "alligator", "crocodile" };
26 System.out.println( findMax( arr, new CaseInsensitiveCompare( ) ) )
27 }
28 }

【问题讨论】:

  • 基本上只是在努力实现使用 findMax 例程和比较器。我还根据问题要求通过数组创建了一堆随机矩形对象
  • 你有一个findMax 例程。您需要做的就是定义您的Comparator&lt;Rectangle&gt;s,然后您就可以插入了。

标签: java arrays comparator rectangles generic-programming


【解决方案1】:

你快到了。

  • 您不能使用 .size(),它只存在于 Collection 对象,而不是原始数组 - 请改用 .length。
  • 一般使用 E 或 T 表示类型,E 表示元素。
  • 请使用大括号保持代码可读性

例子

public static <E> E findMax(E[] arr, Comparator<? super E> 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];
}

我们需要一个比较器来按区域进行比较。

private static class AreaComparator implements Comparator<Rectangle> {
    public int compare(Rectangle lhs, Rectangle rhs) {
        return Double.compare(lhs.getArea(), rhs.getArea());
        // <== delegate to Double.compare() for nice readable solution
    }
}

还有一个 Rectangle 类,我假设你已经有了?这里定义了 getArea()。

private static class Rectangle {
    private double width;
    private double height;
    public Rectangle(double width, double height) {
        super();
        this.width = width;
        this.height = height;
    }
    public double getArea() {
        return width * height;
    }
    @Override
    public String toString() {
        return "Rectangle [width=" + width + ", height=" + height + "]";
    }
}

测试一下

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

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多