-6

I want to make a comparator class that implements the comparator interface. In the class I want to compare 2 of my employee objects based on their ID. The employee class that I have made so far is:

import java.util.ArrayList;


public class Employee {
public int ID_Number;
public String Full_Name;
public double Salary;
static ArrayList<Object> employ = new ArrayList<Object>();


Employee(int id, String name, double sal){
    ID_Number = id;
    Full_Name = name;
    Salary  = sal;
}

}

I'm totally stuck on this and don't have any idea what to do. Can anybody help?

Tobias Funke
  • 1,614
  • 3
  • 13
  • 23

1 Answers1

1

Here's a Comparator inner class from my little project DBvolution:

private static class ClassNameComparator implements Comparator<Class<?>>, Serializable {

    private static final long serialVersionUID = 1L;

    ClassNameComparator() {
    }

    @Override
    public int compare(Class<?> first, Class<?> second) {
        String firstCanonicalName = first.getCanonicalName();
        String secondCanonicalName = second.getCanonicalName();
        if (firstCanonicalName != null && secondCanonicalName != null) {
            return firstCanonicalName.compareTo(secondCanonicalName);
        } else {
            return first.getSimpleName().compareTo(second.getSimpleName());
        }
    }
}

That might look complicated but it's actually simple. The basic principle is below:

class ClassNameComparator implements Comparator<YourClass> {

ClassNameComparator() {
}

@Override
public int compare(YourClass first, YourClass second) {
    if (first > second){
        return 1;
    } else if (first == second){
        return 0;
    } else return -1;
}
}

You'll need to replace YourClass with your class and change the tests to something more appropriate for your objects. Finally remember to check for nulls.