Advertisement
irmantas_radavicius

Untitled

Mar 23rd, 2022
974
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. class MyComp implements Comparator<MyObj> {
  5.    
  6.     public int compare(MyObj mo1, MyObj mo2){
  7.         if (mo1.y < mo2.y)
  8.             return -1;
  9.         if (mo1.y > mo2.y)
  10.             return 1;
  11.         return 0;
  12.     }
  13. }
  14. class MyAnotherComp implements Comparator<MyObj> {
  15.    
  16.     public int compare(MyObj mo1, MyObj mo2){
  17.         if (mo1.z < mo2.z)
  18.             return -1;
  19.         if (mo1.z > mo2.z)
  20.             return 1;
  21.         return 0;
  22.     }
  23. }
  24.  
  25. class MyObj implements Comparable<MyObj> {
  26.     public int x;
  27.     public int y;
  28.     public int z;
  29.    
  30.     public MyObj(int x, int y, int z){
  31.         this.x = x;
  32.         this.y = y;
  33.         this.z = z;
  34.     }
  35.     public int compareTo(MyObj mo){
  36.         if (this.x < mo.x)
  37.             return -1;
  38.         if (this.x > mo.x)
  39.             return 1;
  40.         return 0;
  41.     }
  42.     public String toString(){
  43.         return "[" + x + ", " + y + ", " + z + "]";
  44.     }
  45. }
  46.  
  47. public class Sandbox {  
  48.    
  49.    
  50.     public static void main(String args[]) {       
  51.         try {                      
  52.             MyObj[] a = new MyObj[3];
  53.             a[0] = new MyObj(1,2,3);
  54.             a[1] = new MyObj(4,3,2);
  55.             a[2] = new MyObj(3,1,2);
  56.            
  57.             for(int i = 0; i < a.length; ++i){
  58.                 System.out.print(a[i]);
  59.             }
  60.             System.out.println();
  61.             Arrays.sort(a);
  62.             for(int i = 0; i < a.length; ++i){
  63.                 System.out.print(a[i]);
  64.             }
  65.             System.out.println();
  66.             Arrays.sort(a, new MyComp());
  67.             for(int i = 0; i < a.length; ++i){
  68.                 System.out.print(a[i]);
  69.             }
  70.             System.out.println();
  71.             Arrays.sort(a, new MyAnotherComp());
  72.             for(int i = 0; i < a.length; ++i){
  73.                 System.out.print(a[i]);
  74.             }
  75.             System.out.println();
  76.            
  77.         } catch(Exception e){
  78.             System.out.println(e);         
  79.             System.out.println("Unexpected error, sorry!");
  80.         }          
  81.     }  
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement