Comparator interface

Posted by 1ace1 on Stack Overflow See other posts from Stack Overflow or by 1ace1
Published on 2010-05-16T07:45:48Z Indexed on 2010/05/16 7:50 UTC
Read the original article Hit count: 173

Filed under:

ok I was going to edit my previous question but i wasnt sure if it was the right way to do it so i'll just give another question about Comparator, now i want to be able to sort with different ways. I have a bank checks and i want to sort with checkNumber then checkAmount i managed to do it with checkNumber but couldnt figure out how with checkAmount here is how i did it for checkNumber:

import java.util.Comparator;

public class Check implements Comparator {
    private int checkNumber;
    private String description;
    private double checkAmount;

    public Check() {


    }


    public Check(int newCheckNumber, double newAmountNumber) {

        setCheckNumber(newCheckNumber);
        setAmountNumber(newAmountNumber);
    }

    public String toString() {
        return  checkNumber + "\t\t" + checkAmount;
    }

    public void setCheckNumber(int checkNumber) {
        this.checkNumber = checkNumber;
    }

    public int getCheckNumber() {
        return checkNumber;
    }

    public void setAmountNumber(double amountNumber) {
        this.checkAmount = amountNumber;
    }

    public double getAmountNumber() {
        return checkAmount;
    }

    @Override
    public int compare(Object obj1, Object obj2) {

         int value1 = ((Check) obj1).getCheckNumber();
        int value2 = ((Check) obj2).getCheckNumber();

         int result = 0;

         if (value1 > value2){
             result = 1;
         }
         else if(value1 < value2){
             result = -1;
         }
         return result;
    }
}



import java.util.ArrayList;
import java.util.Collections;

import test.CheckValue;

public class TestCheck {

    public static void main(String[] args) {
        ArrayList List = new ArrayList();


        List.add(new Check(445, 55.0));
        List.add(new Check(101,43.12));
        List.add(new Check(110,101.0));
        List.add(new Check(553,300.21));
        List.add(new Check(123,32.1));


        Collections.sort(List, new Check());

        System.out.println("Check Number - Check Amount");

        for (int i = 0; i < List.size(); i++){

            System.out.println(List.get(i));
        }



    }

}

thank you very much in advance and please tell me if im submiting things in the wrong way.

© Stack Overflow or respective owner

Related posts about java