-4

I wrote user type as below

class Item {
   int first;
   int second;

   public boolean equals(Item p) {
       if(first == p.first && second == p.second ) 
           return true;
       else if(first == p.second && second == p.first)
           return true;
       else
           return false;
   }
   public int hashcode() {
       return Objects.hash(first, second);
   }
   public void set(Object first, Object second) {
       this.first = Integer.parseInt(first.toString());
       this.second = Integer.parseInt(second.toString());
   }

}

However, It doesn't work at all. Did I design the duplicate test incorrectly?

김규덕
  • 19
  • 4
  • 1
    "It doesn't work" is not a meaningful problem statement. Please [edit] your question to include the details of *how* your program doesn't work. – azurefrog May 09 '19 at 19:20
  • Also, if by "duplicate test" you mean your `equals()` method, then yes, you've written it incorrectly. For starters, there are tons of edge cases that you're ignoring, such as what is `p` if `null`? – azurefrog May 09 '19 at 19:22
  • Your `hashCode()` is not consistent with `equals()`. And it's also not named correctly. – shmosel May 09 '19 at 19:25

1 Answers1

2

Some subtle issues:

  • the signature of equals needs to be public boolean equals(Object o) (so, yes, you need to compare against Object, not your direct class)
  • for hashcode, it should be hashCode(). And of corse, two objects that ewuals() deems equal need to have the same hashCode value. Which your implementation does not achieve.

The real lesson here: when you intend to overwrite methods, then put the @Override annotation above it, so that the compiler can tell you when you messed up big, or small.

In your case, you achieved to get both methods wrong that you need to get right when you intend to use your class with any of the java collection contains, such as Map/HashMap.

GhostCat
  • 137,827
  • 25
  • 176
  • 248