0

I am using Processing language (derived from Java PApplet) version 3.01

Here is my code...

  Pig a = new Pig(1);
  Pig b = new Pig(1);
  HashMap<Pig, String> m = new HashMap<Pig, String>();
  m.put(a,"foo");
  String c = m.get(b);
  println(c);  

class Pig {
  int a;
  Pig(int x) { a=x;}
  boolean equals(Pig b) { return b.a==a;}
  int hashCode() { return a;}
}

As you can see I am using Pig for key, I defined the equals and hashCode. I expect output "foo", however, I get output null.

Any idea what is going on here? Why doesn't this work?

John Henckel
  • 10,274
  • 3
  • 79
  • 79
  • You did not add `b` to the HashMap. Therefore you cannot retrieve it, even if there is another object in the HashMap, which's `equals` method returns true. – hotzst Nov 01 '15 at 21:33
  • You didn't override equals. – Alexis C. Nov 01 '15 at 21:33
  • @hotzst : that's precisely what he's trying to do, get "foo" wihtout adding b because a and b should be considered equals. – Mateo Barahona Nov 01 '15 at 21:38
  • HashMap uses the hashCode only as part of its hashing algorithm. Thereby even if an equal element is in the HashMap with the same `hashCode` it will not land in the same bucket. See http://stackoverflow.com/questions/6493605/how-does-a-java-hashmap-handle-different-objects-with-the-same-hash-code – hotzst Nov 01 '15 at 21:44

2 Answers2

1

You didn't override equals(Object), but you did implement an unrelated equals(Pig) method. HashMap uses the former, your method isn't even called.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

Try that, you didn't override Object methods at all / correctly :

class Pig {
    int a;

    Pig(int x) {
      a = x;
    }

    @Override
    public boolean equals(Object b) {
      if(b == null) return false;
      if(!(b instanceof Pig)) return false;
      if(b == this) return true;
      return ((Pig) b).a == a;
    }

    @Override
    public int hashCode() {
      return a;
    }
  }
Mateo Barahona
  • 1,381
  • 8
  • 11