Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1.  
  2. import java.util.Comparator;
  3.  
  4. class Comp {
  5.     public static void main(String[] args) {
  6.         System.out.println(max2(1,2));
  7.  
  8.         Person p1 = new Person(11);
  9.         Person p2 = new Person(20);
  10.  
  11.         System.out.println(max2(p1,p2));
  12.        
  13.         System.out.println(max2(p1,p2,new PersonComp()));
  14.        
  15.         System.out.println(max2(p1,p2,new Comparator<Person>(){
  16.             public int compare(Person a, Person b) {
  17.                 return b.alder - a.alder;
  18.             }
  19.         }));
  20.  
  21.  
  22.     }
  23.  
  24.     public static <T extends Comparable<T>> T max2(T a, T b) {
  25.         if (a.compareTo(b) > 0) return b;
  26.         else return a;
  27.     }
  28.  
  29.     public static <T> T max2(T a, T b, Comparator<T> comp) {
  30.         if (comp.compare(a,b) > 0) return b;
  31.         else return a;
  32.     }
  33. }
  34.  
  35. class Person implements Comparable<Person>{
  36.     int alder;
  37.  
  38.     Person(int a) {
  39.         alder = a;
  40.     }
  41.  
  42.     public String toString() {
  43.         return alder+"";
  44.     }
  45.  
  46.     public int compareTo(Person p) {
  47.         return alder - p.alder;
  48.     }
  49. }
  50.  
  51. class PersonComp implements Comparator<Person> {
  52.     public int compare(Person a, Person b) {
  53.         return (a.alder % 10) - (b.alder % 10);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement