The first chapter after-school exercise 1.15

Rectangle 1.15 define a class that provides getLength getWidth and methods. FindMax prepared using routine in Figure 1-18

One kind of main method, which creates a Rectangle array and according to first identify the biggest area of ​​a Rectangle object, according to the perimeter and find the biggest Rectangle object.

Package com.algorithm.chapterone; 

Import java.util.Comparator; 

/ ** 
 * define a Rectangle class, which provides getLength getWidth and methods. FindMax routine use in the preparation of Figure 1-18 
 * one kind of main method, which creates a Rectangle array and according to first identify the biggest area of a Rectangle object, according to the perimeter and find the biggest Rectangle object. 
 * @Author Gao · Rongzheng 
 * 
 * / 
public  class the Rectangle {
     Private  int length, width; 
    
    public the Rectangle ( int length, int width) {
         the this .length = length;
         the this .width = width; 
    } 
    
    public  int getArea() {
        return length * width;
    }
    
    public int getPerimeter() {
        return (length + width) * 2;
    }
    
    public static <T> T findMax(T[] arr, Comparator<? super T> cmp) {
        int maxIndex = 0;
        for (int i = 0; i < arr.length; i++) {
            if (cmp.compare(arr[i], arr[maxIndex]) > 0) {
                maxIndex = i;
            }
        }
        return arr[maxIndex];
    }
    /**
     * 周长比较器
     * @author Gao·Rongzheng
     *
     */
    public static class PerimeterComparator implements Comparator<Rectangle> {

        @Override
        public int compare(Rectangle o1, Rectangle o2) {
            // TODO Auto-generated method stub
            if (o1.getPerimeter() > o2.getPerimeter()) {
                return 1;
            } else if (o1.getPerimeter() < o2.getPerimeter()) {
                return -1;
            } else {
                return 0;
            }
        }
    }
    
    /**
     * 面积比较器
     * @author Gao·Rongzheng
     *
     */
    public static class AreaComparator implements Comparator<Rectangle> {

        @Override
        public int compare(Rectangle o1, Rectangle o2) {
            // TODO Auto-generated method stub
            if (o1.getArea() > o2.getArea()) {
                return 1;
            } else if (o1.getArea() < o2.getArea()) {
                return -1;
            } else {
                return 0;
            }
        }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Rectangle[] rectangles = {new Rectangle(5, 6), new Rectangle(3, 8), new Rectangle(4, 4), new Rectangle(1, 9)};
        System.out.println(findMax(rectangles, new PerimeterComparator()).getPerimeter());
        System.out.println(findMax(rectangles, new AreaComparator()).getArea());
    }

}

 

Guess you like

Origin www.cnblogs.com/code-future/p/11429619.html