0

Is there a way to temporarily override hashcode and equals in java ? I have a User class with id, name and age attributes. The current equals compares the id, rightly so. So if two ids, are same then the Users are equal.

Now, I have two Lists of User and I want to find users with common names.

Other than looping every element of list1 over every element of list2, I have no other option (java 7). Is there a way, I can temporarily change the behaviour of equals ? In this case, where I am coding the logic for searching users with common names, I want to be able to say if name is same then the users are equal (even though its technically incorrect), without touching the actual User class's equal.

happybuddha
  • 1,271
  • 2
  • 20
  • 40
  • There doesn't seem to be any benefit to overriding `equals` this way. If you were hoping to use `contains`, that would still perform the loop you want to avoid, just hidden away. This sounds like a job for a `Map`. – user2357112 May 09 '18 at 23:11
  • Don’t override equals and hashcode. What you’re looking for is called a Comparator. – Nathan Hughes May 09 '18 at 23:16
  • @user2357112 Agreed. At least it will be the standard java api doing this stuff. Although I wonder if converting two lists to a map and then somehow doing what I want to do would be cost-effective. – happybuddha May 09 '18 at 23:19
  • @NathanHughes I am not looking to sort the elements. I have never used a Comparator to achieve what I am trying to do. Any examples ? – happybuddha May 09 '18 at 23:20
  • Instead of trying to hide the expensive operation, you should replace it by an efficient solution, loop over one list, putting all elements into a `HashMap`, mapping from the desired property (name) to the element, followed by looping over the other list looking up the names. That’s n+m operations instead of n×m operations… – Holger May 18 '18 at 17:32

0 Answers0