1

Possible Duplicate:
Why I’m getting StackOverflowError

I am using two classes: Date and Exam. Date sets a Date object from three integers: day, month,year; Exam sets an Exam object from one String courseName and one Date Object.

I am trying to run this code:

    public Exam(String name, Date d)
    {
        courseName=name;
        examDate=new Date(d);
    }

    //**a method that checks if two dates are equal**
    public boolean equals (Date r)
    {
        return (examDate.equals(r));
    }

    public static void main(String[] args)
    {
        Date d=new Date(11,11,2011);
        String a=new String("OOP");
        Exam b=new Exam(a,d);
        Date c=new Date(11,11,2011);
        System.out.println(b.equals(c));
    }

when I try to run the code I get the error Exception in thread "main" java.lang.StackOverflowError

The error says that the problem is on a line in Date class, which checks if two dates are equal:

public boolean equals (Date d)
{
    return (this.equals(d));
}

I'll be thankful to know why that happens.

Community
  • 1
  • 1
Assaf
  • 1,112
  • 4
  • 14
  • 35

2 Answers2

5
boolean equals(Date d) {
  this.equals(d); 
}

Whatever this class is, the equals method is entirely wrong - it just calls itself, which in turn calls itself, which in turn calls itself, infinitely recursing, until you get a StackOverflowError.

First off: the proper signature for overriding equals is:

boolean equals(Object obj)

Having class specific overrides is just... odd. It looks like perhaps someone was trying to delegate to the default equals() method, but that's not what that's going to do.

If this is a custom Date class, equals should look something like:

boolean equals(Object obj) {
  if (!obj instanceof Date) {
    return false;
  }
  Date other = (Date) obj;
  return this.field1.equals(date.field1) && this.field2.equals(date.field2)...... ;
}

Also, get in the practice now of implementing hashCode any time you implement equals(). It will save you grief down the line.

Why should I override hashCode() when I override equals() method?

Community
  • 1
  • 1
James
  • 8,512
  • 1
  • 26
  • 28
2

As James said, return (this.equals(d)); is definitely wrong. Supposing your Date class has attributes for year, month and day, you should rather try something like

public boolean equals(Object o) {
    if (! o instanceof Date) return false;
    Date d = (Date)o;
    return this.year == d.year && this.month == d.month && this.day == d.day;
}

Note it is important that the static type of the parameter is Object, see the answer of James

gefei
  • 18,922
  • 9
  • 50
  • 67