Guys..

I am trying to figure out Comparator so I can compare Strings in an object array (the object has other data types as well).

I have been hunting around and have come up with this.. but I cant get it to work --> Can anyone point me in the right direction.. (if find the javadoc on the Comparator class is not very helpful)

public class NameComparator implements Comparator
{
    public static int compareNames(BankCustomer customerOne, BankCustomer customerTwo)
    {

        String CustomerOneName = customerOne.getFullName();

        String CustomerTwoName = customerTwo.getFullName();

        return(CustomerOneName.compareTo(CustomerTwoName));
    }

}

Or how do I just call it from within my main class?

I tried Comparator c = new Comparator(); and also all other combos.. but i am a bit lost here...

anyone?

Recommended Answers

All 3 Replies

You need this import

import java.util.Comparator;

Then you need to implment this method, you dont have to use it but since your implementing Comparator, you need to implement all the methods in Comparator.

@Override
	public int compare(Object arg0, Object arg1) {
		// TODO Auto-generated method stub
		return 0;
	}

You use your comparator when you try to sort the array, for example

Arrays.sort(myArrayOfBankCustomers, new NameComparator());

However, you haven't implemented the Comparator interface properly. You need your method to match the name, scope, and return type EXACTLY to those defined in the Comparator, ie

public int compare(BankCustomer customerOne, BankCustomer customerTwo);


You'll probably get a warning about "raw types", but you can probably ignore that just for the moment.

Hey thanks guys..

I got it working.. but then it wasn't sorting... so I looked around more.. and I changed it (to as follows), and now it works!

Thanks again for your help!

public class NameComparator implements Comparator
{
    @Override
    public int compare(Object ObjectOne, Object ObjectTwo)
    {
        //parameter are of type Object, so we have to downcast it to Employee objects

        String CustomerOneName = ((BankCustomer)ObjectOne).getSurname();
        String CustomerTwoName = ((BankCustomer)ObjectTwo).getSurname();

        //uses compareTo method of String class to compare names of the employee

        return(CustomerOneName.compareTo(CustomerTwoName));
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.