Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. import java.util.Comparator;
  2.  
  3. public class OnePointFifteen {
  4.  
  5. public static void main(String[] args) throws Exception
  6. {
  7. // TODO Auto-generated method stub
  8. System.out.println(findMax(new Rectangle[] { new Rectangle(1, 2), new Rectangle(3, 4), new Rectangle(2,5) }, new AreaComparator()));
  9. System.out.println(findMax(new Rectangle[] { new Rectangle(4, 5), new Rectangle(3, 4), new Rectangle(10,20) }, new PerimeterComparator()));
  10. }
  11.  
  12. private static class Rectangle {
  13. private double width;
  14. private double height;
  15. public Rectangle(double width, double height) {
  16. super();
  17. this.width = width;
  18. this.height = height;
  19. }
  20. public double getArea() {
  21. return width * height;
  22. }
  23. public double getPerimeter() {
  24. return (2*width) * (2*height);
  25. }
  26. @Override
  27. public String toString() {
  28. return "Rectangle [width=" + width + ", height=" + height + "]";
  29. }
  30. }
  31. public static <E> E findMax(E[] arr, Comparator<? super E> cmp) {
  32. int maxIndex = 0;
  33. for (int i = 1; i < arr.length; i++) {
  34. if (cmp.compare(arr[i], arr[maxIndex]) > 0) {
  35. maxIndex = i;
  36. }
  37. }
  38. return arr[maxIndex];
  39. }
  40. private static class AreaComparator implements Comparator<Rectangle> {
  41. public int compare(Rectangle lhs, Rectangle rhs) {
  42. return Double.compare(lhs.getArea(), rhs.getArea());
  43. // <== delegate to Double.compare() for nice readable solution
  44. }
  45.  
  46. }
  47. private static class PerimeterComparator implements Comparator<Rectangle> {
  48. public int compare(Rectangle lhs, Rectangle rhs) {
  49. return Double.compare(lhs.getPerimeter(), rhs.getPerimeter());
  50. // <== delegate to Double.compare() for nice readable solution
  51. }
  52.  
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement