• Using an object as key for a hashmap in Java

    by  • July 10, 2008 • java • 1 Comment

    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.

    About

    .NET developer at thetrainline.com, previously web developer at MRM Meteorite. Awarded a PhD in misbehaviour detection in wireless ad-hoc networks.A keen C# ASP.net developer bridging the gap with APIs and JavaScript frameworks, one web app at a time.

    http://www.paulkiddie.com

    One Response to Using an object as key for a hashmap in Java

    1. Prashant
      May 19, 2012 at 4:43 pm

      Thanks, this really helped……….:)

    Leave a Reply

    Your email address will not be published. Required fields are marked *