Be careful on contains() method

It is very important to understand how to use contains() method in Map/Set, otherwise unexpected result you may get.

  1. A common mistake
    You will not able to get "green" Apple object in this example since the one you stored at the beginning and the one you queried is two different objects.

    import java.util.HashMap;
    public class Apple {
        private String color;        
        public Apple(String color) {
            this.color = color;
        }        
        public boolean equals(Object obj) {
            if (!(obj instanceof Apple))
                return false;   
            if (obj == this)
                return true;
            return this.color.equals(((Apple) obj).color);
        }        
        public static void main(String[] args) {
            Apple a1 = new Apple("green");
            Apple a2 = new Apple("red");         
            //hashMap stores apple type and its quantity
            HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
            m.put(a1, 10);
            m.put(a2, 20);
            System.out.println(m.get(new Apple("green")));
        }
    }
    

2, fix the issue
You have to override hashCode() to object you want to compare, HashCode() will be called inside contains() method from Map/Set to identify if two object are the same or not.

    import java.util.HashMap;
    public class Apple {
        private String color;

        public Apple(String color) {
            this.color = color;
        }
        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof Apple))
                return false;   
            if (obj == this)
                return true;
            return this.color.equals(((Apple) obj).color);
        }
        @Override  
          public int hashCode() {  
            String s = thiscolor;
            return s.hashCode();
        }

        public static void main(String[] args) {
            Apple a1 = new Apple("green");
            Apple a2 = new Apple("red");

            //hashMap stores apple type and its quantity
            HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
            m.put(a1, 10);
            m.put(a2, 20);
            System.out.println(m.get(new Apple("green")));
        }
    }