Is it possible in java make something like Comparator but for implementing custom equals() and hashCode()

Yes it is possible to do such a thing. (And people have done it.) But it won’t allow you to put your objects into a HashMap, HashSet, etc. That is because the standard collection classes expect the key objects themselves to provide the equals and hashCode methods. (That is the way they are designed to … Read more

hashCode in case classes in Scala

As my professor used to say, only the code tells the truth! So just take a look at the code that is generated for: case class A(i: Int, s: String) We can instruct the Scala compiler to show us the generated code after the different phases, here after the typechecker: % scalac -Xprint:typer test.scala [[syntax … Read more

GetHashCode override of object containing generic array

Because of the problems raised in this thread, I’m posting another reply showing what happens if you get it wrong… mainly, that you can’t use the array’s GetHashCode(); the correct behaviour is that no warnings are printed when you run it… switch the comments to fix it: using System; using System.Collections.Generic; using System.Linq; static class … Read more

How does Java order items in a HashMap or a HashTable?

java.util.HashMap is unordered; you can’t and shouldn’t assume anything beyond that. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. java.util.LinkedHashMap uses insertion-order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all … Read more

toString(), equals(), and hashCode() in an interface

It sounds like you want to force your classes to override the default implementations of those methods. If so, the way to do this is to declare an abstract superclass that has the methods declared as abstract. For example: public abstract class MyBaseClass implements … /* existing interface(s) */ { public abstract boolean equals(Object other); … Read more

How is hashCode() calculated in Java

The value returned by hashCode() is by no means guaranteed to be the memory address of the object. I’m not sure of the implementation in the Object class, but keep in mind most classes will override hashCode() such that two instances that are semantically equivalent (but are not the same instance) will hash to the … Read more