June 05, 2011

How to use Comparable and Comparator Interfaces in Java

package com.nano.test;
import java.util.*;
class Employee implements Comparable {

    int EmpID;
    String Ename;
    double Sal;
    static int i;

    public Employee() {
        EmpID = i++;
        Ename = "dont know";
        Sal = 0.0;
    }

    public Employee(String ename, double sal) {
        EmpID = i++;
        Ename = ename;
        Sal = sal;
    }

    public String toString() {
        return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
    }

    public int compareTo(Object o1) {
        if (this.Sal == ((Employee) o1).Sal)
            return 0;
        else if ((this.Sal) > ((Employee) o1).Sal)
            return 1;
        else
            return -1;
    }
}


public class ComparableDemo{

    public static void main(String[] args) {

        List ts1 = new ArrayList();
        ts1.add(new Employee ("AaAa",40000.00));
        ts1.add(new Employee ("aAaA",20000.00));
        ts1.add(new Employee ("AaA",50000.00));
        ts1.add(new Employee ("aAa",70000.00));
        Collections.sort(ts1);
        Iterator itr = ts1.iterator();

        while(itr.hasNext()){
            Object element = itr.next();
            System.out.println(element + "\n");
          
        }
        String line = "this is a sentence hai";
        String lastWord = line.substring(line.lastIndexOf(' ') + 1);
        System.out.println("Lastword:"+lastWord);
      
        ComparableDemo cb= new ComparableDemo();
        int rn =cb.reverseNumber(4322);
        System.out.println("ReverseNumber"+rn);
    }
    int reverseNumber(int number)
    {
      int reversedNumber = 0;
      while(number != 0)
      {
         reversedNumber = (reversedNumber * 10) + (number % 10);System.out.println("red"+reversedNumber);
         number /= 10;
      }
      return reversedNumber;
    }

}

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts