2015-02-10 18 views
1

問題:定義一個提供getLength和getWidth方法的Rectangle類。使用圖1.18中的 findMax例程,編寫一個main,它創建一個Rectangle 的數組,並根據面積,然後根據周長找到最大的Rectangle。如何編寫這個通用對象程序?

我到目前爲止所做的是在構造函數中創建一個帶參數寬度和高度的類矩形。之後,我實現了兩個getter方法,其中實例變量的寬度和高度分別返回其各自的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 } 
+0

基本上只是使用findMax例程和比較的實施掙扎。我還通過一個數組創建了一堆隨機矩形對象,如您有'findMax'例程的問題 – btrballin 2015-02-10 06:05:03

+0

。所有你需要做的就是定義你的'Comparator ',你可以插入。 – 2015-02-10 06:07:00

回答

0

你幾乎沒有。

  • 您不能使用.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 
    } 
} 

和一個矩形類,我假設你已經?這裏它定義了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())); 
}