Stop(Id, Name) is a java class, and i want to store these stop objects in a java.util.Set and those objects should be sorted according to the Id of Stop.
this is my comparator
public class StopsComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Stop stop1 = (Stop)o1;
Stop stop2 = (Stop)o2;
return stop1.getStopId().compareTo(stop2.getStopId());
}
}
private Set<Stop> stops = new TreeSet<Stop>(new StopsComparator());
but its not giving correct result?
Does Stop implement an equals method that works on the same field as your comparator? If not then that will lead to problems. You also might want to switch to have your object implement Comparable (although that wouldn’t fix the problem you’re seeing).
Once you implement an
equals()method, then you should also implement ahashCode()method that works on the same field.Findbugs would have probably told you these things. Its extremely useful.