jekaterina jekaterina - 4 days ago 5
Java Question

compareTo causes stack overflow

I wrote a class Day and now I wanna compare the two objects of day to see which day is after.

But the problem is when I tried to use compareTo to compare the two days, it causes stack Overflow

This is the day class I created, please help to see why I can't use compareTo.

public class Day implements Cloneable,Comparable<Day>{

private int year;
private int month;
private int day;

private static final String MonthNames="JanFebMarMayJunJulAugSepOctNovDec";
//Constructor
public Day(int y, int m, int d) {
this.year=y;
this.month=m;
this.day=d;
}


public void set(String sDay)
{
String[] sDayParts = sDay.split("-");
this.year = Integer.parseInt(sDayParts[2]);
this.day = Integer.parseInt(sDayParts[0]);
this.month = MonthNames.indexOf(sDayParts[1])/3+1;
}

public Day(String sDay)
{
set(sDay);


}


// Return a string for the day like dd MMM yyyy
public String toString() {

return day+"-"+ MonthNames.substring((month-1)*3,month*3)+ "-"+ year;
}



@Override
public int compareTo(Day another)
{

return this.compareTo(another);
}

Answer

You have a method which calls itseld endlessly until the stack blows up.

@Override
public int compareTo(Day another)
{
    return this.compareTo(another); // calls itself until the stack is exhuased
}

What you need to do is to compare the fields of the class. e.g.

@Override
public int compareTo(Day d) {
    int cmp = Integer.compare(year, d.year);
    if (cmp == 0) cmp = Integer.compare(month, d.month);
    if (cmp == 0) cmp = Integer.compare(day, d.day);
    return cmp;
}
Comments