2 Replies Latest reply on Dec 10, 2013 12:09 AM by MuhammadKhojaye

    Custom Objects and Hash Maps


      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");


      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 ??