Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Comparator;
- public class OnePointFifteen {
- public static void main(String[] args) throws Exception
- {
- // TODO Auto-generated method stub
- System.out.println(findMax(new Rectangle[] { new Rectangle(1, 2), new Rectangle(3, 4), new Rectangle(2,5) }, new AreaComparator()));
- System.out.println(findMax(new Rectangle[] { new Rectangle(4, 5), new Rectangle(3, 4), new Rectangle(10,20) }, new PerimeterComparator()));
- }
- 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;
- }
- public double getPerimeter() {
- return (2*width) * (2*height);
- }
- @Override
- public String toString() {
- return "Rectangle [width=" + width + ", height=" + height + "]";
- }
- }
- 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
- }
- }
- private static class PerimeterComparator implements Comparator<Rectangle> {
- public int compare(Rectangle lhs, Rectangle rhs) {
- return Double.compare(lhs.getPerimeter(), rhs.getPerimeter());
- // <== delegate to Double.compare() for nice readable solution
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement