3

Why don't hashCode() and equals() work when a List implemented object stores its own object as a element?

10
  • Did you implement them correctly?
    – Kayaman
    Nov 12, 2013 at 9:14
  • 5
    Where is the code which doesn't seem to be working?!
    – Rahul
    Nov 12, 2013 at 9:14
  • 2
    That's an excellent question. I don't understand why you're getting close votes and down votes. I'll try to answer it before it gets closed. Nov 12, 2013 at 9:17
  • 1
    @David I think people want a test case to show it happening Nov 12, 2013 at 9:17
  • 1
    Not difficult - public class ListProblem { public static void main (String [] args) { List<Object> testCase = new ArrayList<Object>(); testCase.add(testCase); System.out.println(testCase.hashCode()); } } Nov 12, 2013 at 9:19

1 Answer 1

7

A List bases its equals relation on the contents of the list. If one of the members is the list itself, infinite recursion ensues. The same problem occurs with hashCode.

5
  • 1
    Nice way of phrasing it. I wish I'd spent my time writing an answer, instead of messing round posting the test case. I have nothing to add to this. Nov 12, 2013 at 9:22
  • FWIW I haven't profited from your test case---I was spending time writing my wrong answer :) Nov 12, 2013 at 10:04
  • 1
    Oh, I wasn't suggesting for a moment that you had. I know you're quite capable of working this stuff out for yourself. Nov 12, 2013 at 10:13
  • @MarkoTopolnik So is there is any way I can store List instance inside its own instance and use it further. thanks Nov 16, 2013 at 8:35
  • 1
    You could subclass the list implementation you are using and improve the equals and hashCode to take care of your concern. But I would advise just avoiding the need to have a list as its own member. Nov 16, 2013 at 15:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.