Paul Kiddie

Using an object as key for a hashmap in Java

July 10, 2008

I came across a situation recently where I needed to use an object as a key for as hashmap. According to this Java post all you need to do is to make your class override the Object.equals() and Object.hashCode() methods.

I wanted to represent a ‘flow’ in a network, with my contstructor looking something like the following:

public Flow(NetAddress src,NetAddress dst) { this.flowSrc = src; this.flowDst = dst; }

now I use the following overrides:

public int hashCode() { return flowSrc.toString().hashCode() ^ flowDst.toString().hashCode(); }

public boolean equals(Object o) { Flow flow = (Flow)o;

if (flow.flowSrc.equals(flowSrc) && flow.flowDst.equals(flowDst)) { return true; }

return false; }

and when i’m testing whether a particular key exists in the hashmap I can create a new Flow and check directly whether it currently exists as a key in the hashmap. Typically, if you didn’t implement this, then two flow objects would have different references (even if they have the same NetAddress contents) and would not be equal.


👋 I'm Paul Kiddie, a software engineer working in London. I'm currently working as a Principal Engineer at trainline.