1. package com.instanceofjava;
  2.  
  3. import java.util.Comparable;
  4.  
  5. public class Employee implements Comparable<Employee> {
  6.  
  7.  int id;
  8.  String name;
  9.  
  10.  public Employee(int id, String name) {
  11. this.id=id; 
  12. this.name=name;
  13.  }
  14.  
  15.  public int getId() {
  16. return id;
  17.  }
  18.  
  19.  public void setId(int id) {
  20.   this.id = id;
  21.  }
  22.  
  23.  public String getName() {
  24. return name;
  25.  }
  26.  
  27.  public void setName(String name) {
  28.   this.name = name;
  29.  }
  30.  
  31.  @Override
  32.  public int compareTo(Employee e) {
  33.  
  34.  Integer i= this.getId();
  35.  Integer j=e.getId();
  36.  
  37.      if (this.getId() == e.getId())
  38.        return 0;
  39.       if (this.getId() < e.getId())
  40.         return 1;
  41.       if (this.getId() > e.getId())
  42.        return -1;
  43.       return 0;
  44. }
  45. }

  1. package com.oops;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Iterator;
  5. import java.io.*;
  6.   class Main{  
  7.  
  8. public static void main(String args[]){
  9.  
  10.  ArrayList al=new ArrayList();  
  11.  
  12.  al.add(new Employee(101,"Indhu"));
  13. al.add(new Employee(106,"Sindhu"));
  14.  al.add(new Employee(105,"Swathi"));  
  15. Collections.sort(al);
  16.  
  17. Iterator itr=al.iterator();   
  18.  
  19. while(itr.hasNext()){
  20.  
  21.    Employee st=(Employee)itr.next();
  22.    System.out.println(st.id +" "+st.name );   
  23.  
  24.   } 
  25. }  
  26.  
  27. }  
Output:
  1. Indhu 
  2. Swathi 
  3. Sindhu

 

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu