Java 如何编写这个通用对象程序?
问题:定义一个提供getLength和getWidth方法的矩形类。使用 findMax例程在图1.18中,编写一个main来创建一个矩形数组 首先根据面积,然后根据周长找到最大的矩形 到目前为止,我所做的是在构造函数中创建一个带有参数width和height的类矩形。之后,我实现了两个getter方法,其中实例变量width和height返回各自的getter方法。所以我需要第二部分的帮助 图1.18Java 如何编写这个通用对象程序?,java,arrays,comparator,rectangles,generic-programming,Java,Arrays,Comparator,Rectangles,Generic Programming,问题:定义一个提供getLength和getWidth方法的矩形类。使用 findMax例程在图1.18中,编写一个main来创建一个矩形数组 首先根据面积,然后根据周长找到最大的矩形 到目前为止,我所做的是在构造函数中创建一个带有参数width和height的类矩形。之后,我实现了两个getter方法,其中实例变量width和height返回各自的getter方法。所以我需要第二部分的帮助 图1.18 1 // Generic findMax, with a function object.
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 }
1//Generic findMax,带有函数对象。
2//前提条件:a.size()>0。
3公共静态
4 AnyType findMax(AnyType[]arr,Comparator您就快到了
- 不能使用.size(),它只存在于集合对象中,而不存在于基元数组中-请改用.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];
}
测试一下
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()));
}
基本上,我只是在努力实现使用findMax例程和比较器。我还根据问题的需要通过数组创建了一组随机矩形对象。你有一个findMax
例程。你所需要做的就是定义你的比较器,然后你就可以插入了。
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()));
}