Issues with Java HashMap and key Object I rolled myself

前端 未结 1 348
南方客
南方客 2021-01-21 19:12

So, I\'m trying to use a HashMap to map my own Object to a String value. My object is below (with some code removed for brevity)



        
相关标签:
1条回答
  • 2021-01-21 19:51

    You're not overriding Object.equals - you're overloading it because of the parameter type. Your diagnostic code calls your overload, but the map code doesn't (as it doesn't know about it).

    You need a method with a signature of

    public boolean equals(Object other)
    

    If you use the @Override annotation you'll get an error if you fail to override something properly.

    You'll need to check whether other is an instance of RouteHeadSignPair first, then cast. If you make the RouteHeadSignPair class final, you won't need to worry about whether or not it's the exact same class, etc.

    Note that your hash codes will collide unnecessarily, by the way - if you use both the route and the headSign hashes to generate your hash code, it may help your map lookups to be more efficient. (If there are several instances with the same route but different head signs, it's useful if the map doesn't have to check for equality on all of them when looking up a key.)

    0 讨论(0)
提交回复
热议问题