1

Sorry if this is basic but I am starting java and this is not any assignment but why is my simple test program failing ?

static public class pair
 {
     public int x;
     public int y;
     public pair(int a , int b)
     {
         x = a;
         y = b;
     }
 }
 public static void main(String args[])
 {
     HashMap<pair,Integer>m = new HashMap<pair,Integer>();
     m.put(new pair(1,2), 3);
     if(m.containsKey(new pair(1,2)))
     {
         System.out.println("is there " + m.get(new pair(1,2)));
     }

 }
ashok v
  • 408
  • 3
  • 11

1 Answers1

4

It's obvious - you didn't override equals and hashCode in your badly named pair class.

Read chapter 3 of Joshua Bloch's "Effective Java" to see how to do it properly.

It's the difference between deep and shallow equals. When you don't override equals, you compare object references. The references to your two instances with identical data are different; they are not shallow equal.

new pair(1,2).equals(new pair(1,2)) // returns false
new pair(1,2) == new pair(1,2) // returns false

When you override equals to compare the contents of the class you have a chance if you do it properly.

new pair(1,2).equals(new pair(1,2)) // will return true after override 
new pair(1,2) == new pair(1,2) // returns false

Learn and follow Java coding standards: should be Pair, not pair.

Your Pair class would be more useful as a generic:

public class Pair<U, V> {
    public final U u;
    public final V v;

    public Pair<U, V>(U foo, V bar) {   
       this.u = foo;
       this.v = bar;
    }

    // override equals and hashCode

}

Is there a Pair class in JDK8? Interesting discussion here.

Community
  • 1
  • 1
duffymo
  • 305,152
  • 44
  • 369
  • 561