-2

I'm trying to find the fastest way to find a key in a HashMap and return it.

I tried using containsKey but I'm initializing the object before this so the hashcode is different and it can't find it.

I used linear search like this:

Box b = null;
Box box = new Box(10, 5);
for (Box e : cells.keySet()) {
    if (box.equals(e)) {
        contains = true;
        b = e;
    }
}

Box is a class that contains x and y fields. It works fine but I was wondering if there is a faster way to do it.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • then you should override `hashCode()` so that objects with the same values get the same hashcodes. – Jack Flamp Jun 29 '18 at 10:57
  • 1
    If that code works, `containsKey` will also work. **Except** you override `equals` but forget to also override the `hashCode` method. Which, by the way, violates the contract. If you ever implement a custom `equals` you **must** also implement `hashCode` with the same logic. – Zabuzard Jun 29 '18 at 10:58
  • Ok that makes much more sense. you are right I didn't override hashCode. Thanks – Maher Raess Jun 29 '18 at 12:12

1 Answers1

1

You need to override hashcode() and equals() if you Box class first to be able to deal good with HashMap


Then you can simply do :

Box box = new Box(10, 5);
Box b = cells.containsKey(box) ? box : null; 
azro
  • 53,056
  • 7
  • 34
  • 70
  • One more thing to keep in mind: elements that are used as keys, should be immutable - at least the properties used in `equals()` and `hashCode()` should not be changeable (or in short: the hashcode for a key should never change). Mutable keys are a bad thing in maps which can lead to hard to track bugs. – Thomas Jun 29 '18 at 11:02