I am implementing my own Java class for sorting a List<T> in eclipse. I made break points in comparsion statements and it does not work as I unexpected!
Here is the code :
if(doy2 < don && doy1>don)
{
return 1;
}
else if (doy2 > don && doy1<don)
{
return -1;
}
else
{
return 0;
}
Even though the doy2 > don && doy1<don statement evaluates to true, and the code reaches return -1, but it also goes to else part and return 0. Why exactly?
Edited: The Complete code
public class DateCompartor implements Comparator<BirthdayContact> {
@Override
public int compare(BirthdayContact arg0, BirthdayContact arg1) {
Date now=new Date();
Date bd1=arg0.GetBirthDay();
Date bd2=arg1.GetBirthDay();
DateTime dt1=new DateTime(bd1);
DateTime dtnow=new DateTime(now);
DateTime dt2=new DateTime(bd2);
int doy1=dt1.getDayOfYear();
int doy2=dt2.getDayOfYear();
int don=dtnow.getDayOfYear();
if(doy2 < don && doy1>don)
{
return 1;
}
else if (doy2 > don && doy1<don)
{
return -1;
}
else
{
return 0;
}
}
}
I am comparing two dates with current date, and which ever is closer to current date, should get upper in the list.
I’d rebuild your code and step through it again. The ‘weirdness’ that you note might be due to the source and bytecode being out of synch.
I’d ask that you post the entire Comparable implementation. Comparator usually compares two objects, but your comparison statements appear to involve three. Perhaps you can clarify exactly what you’re doing.
Be assured that your code is incorrect. You have a mental model of how this should work in mind, but your assumptions don’t match reality. Your job is to bring them back into harmony.
UPDATE:
Given the new information, I’d certainly not code it the way you did. I’d calculate the difference from each date to today’s time and compare those. I’m not interested enough to test it out myself. See if that works out better for you.