2 Replies Latest reply: Dec 9, 2013 6:09 PM by MuhammadKhojaye RSS

    Custom Objects and Hash Maps

    891071

      Hi All ,

       

      I am trying the below piece of code.

      class dog{

        private String name;

        public dog(String n){ name = n; }

        public String getname(){

      return name;

        }

      public void setname(String n){ name =n;}

        public boolean equals(Object o)

            {

        if (( o instanceof dog )&& (((dog)o).name.equals(name)))

                   return true;

                 else return false;

              }

        public int  hashcode(){

      return name.length();

        }

      public String toString(){

      return "Name:"+name;

        }

      }

      This is my Dog class . Now in Main method , I am trying to do the following

         Map<Object,Object> m = new HashMap <Object, Object>();

      dog p = new dog("GM");

      dog q = new dog ("GM");

        System.out.println(p.equals(q));

      m.put ( new dog("GM"),"K2");  

        System.out.println(m.get(new dog("GM")));

      I am getting a true and a null value. i Was expecting a K2 instead of null . Can somebody help me with this . I have overridden hashcode and equals methods . What is the thing i am missing ??