Avoiding Negative Hash Codes from Java's String.hashCode() in Sharding Scenarios

When sharding data by a non-integer primary key or a composite key (usually concatenated in to a string), developers often rely on Java's built-in String.hashCode() method to derive a hash value, which is then used for modulo-based sharding. While convenient, this approach can produce negative hash codes, leading to invalid shard numbers. Under ...

Posted on Tue, 19 May 2026 15:09:12 +0000 by brianbehrens

Why hashCode Must Be Overridden When equals Is Overridden in Java

Entity Class Definition Let's define a simple Rectangle class that overrides the equals method to compare objects based on their width and height values instead of reference equality. class Rectangle { private int width; private int height; public int getWidth() { return width; } public void setWidth(int width) { ...

Posted on Wed, 13 May 2026 13:15:07 +0000 by nolos

Implementing Custom Objects as HashMap Keys in Java

In Java, the HashMap implementation uses the hashCode() method to determine the storage bucket for a key and the equals() method to check for key equality. The default implementation in the Object class generates a hash code based on the object's memory address. This behavior creates a problem when using custom objects as keys: two distinct ins ...

Posted on Sat, 09 May 2026 05:35:46 +0000 by elbowgrease