Advertisement
apl-mhd

spring 2017 problem7

Jan 12th, 2018
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. //problem a
  2.  
  3.  
  4.  
  5. public  static <T extends Comparable<T>> void sort(ArrayList<T> arr, Boolean tf){
  6.  
  7.         if(!tf){
  8.  
  9.             Collections.sort(arr, new Comparator<T>(){
  10.  
  11.                 @Override
  12.                 public  int compare(T a, T b){
  13.  
  14.                     return a.compareTo(b);
  15.                 }
  16.             });
  17.         }
  18.  
  19.         else
  20.             Collections.sort(arr,new Comparator<T>(){
  21.  
  22.  
  23.                 @Override
  24.                 public  int compare(T a, T b){
  25.  
  26.                     return b.compareTo(a);
  27.                 }
  28.             });
  29.  
  30.     }
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47. import java.util.ArrayList;
  48. import java.util.Collections;
  49.  
  50. public class TestGeneric {
  51. //problem b    
  52.  
  53. public static void main(String[] args) {
  54.  
  55.  
  56.  
  57.         ArrayList<BankAccount> accounts=new ArrayList<BankAccount>();
  58.         accounts.add(new BankAccount("Rasha", "011123", 12000));
  59.         accounts.add(new BankAccount("Keya", "011124", 10500));
  60.         accounts.add(new BankAccount("Asad", "011125", 100000));
  61.  
  62.         Collections.sort(accounts);
  63.         System.out.println("Accounts sorted in Ascending order:");
  64.         for(BankAccount b: accounts)
  65.             System.out.println(b);
  66.     }
  67. }
  68. class BankAccount  implements Comparable<BankAccount>{
  69.  
  70.  
  71.     String name, id;
  72.     double balance;
  73.     public BankAccount(String name, String id, double balance){
  74.         this.name = name;
  75.         this.id = id;
  76.         this.balance = balance;
  77.     }
  78.  
  79.  
  80.  
  81.  
  82.     @Override
  83.     public int compareTo(BankAccount o) {
  84.  
  85.         return (int)this.balance -(int)o.balance;
  86.     }
  87.  
  88.  
  89.  
  90.  
  91.     @Override
  92.     public String toString() {
  93.  
  94.         return name+"-"+id+"-"+(int)balance;
  95.     }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement