2016-11-28 204 views
-2

我写了一天类,现在我想比较一天中的两个对象,以查看哪一天是在之后。compareTo导致堆栈溢出

但问题是,当我试图用的compareTo到两天相比,它会导致堆栈溢出

这是一天班,我创建,请帮忙看看,为什么我不能使用的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); 
} 
+6

当然是的。你所有的compareTo方法都会调用它自己! –

回答

4

你有一种方法,无休止地调用itseld,直到堆栈爆炸。

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

你需要做的是比较类的字段。例如

@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; 
} 
0

你有一个很好的无限递归正在进行。

@Override 
public int compareTo(Day another) 
{ 

    return this.compareTo(another); 
} 

这是一个递归调用。您必须实际实施您自己的compareTo机身,例如检查日期