数据结构练习题1.13
1 package Chapter01; 2 3 import java.util.Comparator; 4 5 public class Rectangle { 6 7 private int length; 8 private int width; 9 10 public Rectangle(int length, int width) { 11 this.length = length; 12 this.width = width; 13 } 14 15 public int getLength() { 16 return length; 17 } 18 public void setLength(int length) { 19 this.length = length; 20 } 21 22 public int getWidth() { 23 return width; 24 } 25 public void setWidth(int width) { 26 this.width = width; 27 } 28 29 public int getArea() { 30 return length*width; 31 } 32 public int getPerimeter() { 33 return length*2 + width*2; 34 } 35 36 public String getObject() { 37 return "("+length+","+width+")"; 38 } 39 public static <AnyType> 40 AnyType findMax(AnyType[] arr, Comparator<? super AnyType> cmp) { 41 42 int maxIndex = 0; 43 44 for(int i = 1; i < arr.length; i++) 45 if(cmp.compare(arr[i], arr[maxIndex]) > 0) 46 maxIndex = i; 47 48 return arr[maxIndex]; 49 } 50 51 public static class areaCompare implements Comparator<Rectangle> { 52 @Override 53 public int compare(Rectangle o1, Rectangle o2) { 54 // TODO Auto-generated method stub 55 if(o1.getArea() > o2.getArea()) { 56 return 1; 57 }else if(o1.getArea() == o2.getArea()) { 58 return 0; 59 }else{ 60 return -1; 61 } 62 } 63 } 64 65 public static class perimeterCompare implements Comparator<Rectangle> { 66 @Override 67 public int compare(Rectangle o1, Rectangle o2) { 68 // TODO Auto-generated method stub 69 if(o1.getPerimeter() > o2.getPerimeter()) { 70 return 1; 71 }else if(o1.getPerimeter() == o2.getPerimeter()) { 72 return 0; 73 }else{ 74 return -1; 75 } 76 } 77 } 78 79 public static void main(String[] args) { 80 Rectangle[] arr = new Rectangle[] { 81 new Rectangle(10, 20), new Rectangle(2, 65), 82 new Rectangle(3, 10), new Rectangle(6, 20) 83 }; 84 85 System.out.println("面积最大:"+findMax(arr, new areaCompare()).getObject()); 86 System.out.println("周长最长:"+findMax(arr, new perimeterCompare()).getObject()); 87 } 88 }