Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package linkedList;
  2.  
  3. import java.util.*;
  4.  
  5. public class JavaComparable {
  6.    
  7.     public static void main(String[] args){
  8.         Student st1=new Student();
  9.         st1.setId(2);
  10.         Student st2=new Student();
  11.         st2.setId(1);
  12.         LinkedList ll=new LinkedList();
  13.         ll.add(st1);
  14.         ll.add(st2);
  15.         System.out.print("before sort: ");
  16.         for(int i=0;i<ll.size();i++){
  17.             System.out.print(((Student)ll.get(i)).getId()+" ");
  18.         }
  19.         System.out.println("");
  20.         Collections.sort(ll);
  21.         System.out.print("after sort: ");
  22.         for(int i=0;i<ll.size();i++){
  23.             System.out.print(((Student)ll.get(i)).getId()+" ");
  24.         }
  25.     }
  26.  
  27. }
  28.  
  29. class Student implements Comparable{
  30.     int id;
  31.     public int getId() {
  32.         return id;
  33.     }
  34.     public void setId(int id) {
  35.         this.id = id;
  36.     }
  37.     @Override
  38.     public int compareTo(Object o) {
  39.        
  40.         int id;
  41.         if(o instanceof Student){
  42.             id=((Student)o).getId();
  43.         }else{
  44.             throw new RuntimeException("wrong type");
  45.         }
  46.        
  47.         if(this.id>id){
  48.             return 1;
  49.         }else if(this.id<id){
  50.             return -1;
  51.         }else{
  52.             return 0;
  53.         }
  54.     }
  55.    
  56. }