Overriding equals() & hashCode() in sub classes … considering super fields

Children should not examine the private members of their parents But obviously, all significant fields should be taken into account for equality and hashing. Fortunately, you you can easily satisfy both rules. Assuming you’re not stuck using the NetBeans-generated equals and hashcode, you can modify Hominidae’s equals method to use instanceof comparison rather than class … Read more

Why doesn’t String’s hashCode() cache 0?

You’re worrying about nothing. Here’s a way to think about this issue. Suppose you have an application that does nothing but sit around hashing Strings all year long. Let’s say it takes a thousand strings, all in memory, calls hashCode() on them repeatedly in round-robin fashion, a million times through, then gets another thousand new … Read more

What is an object’s hash code if hashCode() is not overridden?

In HotSpot JVM by default on the first invocation of non-overloaded Object.hashCode or System.identityHashCode a random number is generated and stored in the object header. The consequent calls to Object.hashCode or System.identityHashCode just extract this value from the header. By default it has nothing in common with object content or object location, just random number. … Read more

What’s a good recipe for overriding hashcode in Dart?

The quiver package provides helper functions hash2, hash3, etc., which simplify the task of implementing hashCode, with some assurance that it works properly under the Dart VM and when compiled to JavaScript. import ‘package:quiver/core.dart’; class Person { String name; int age; Person(this.name, this.age); bool operator ==(o) => o is Person && name == o.name && … Read more