HashMap is working fine. Just because you create two new objects with the same name does not mean that the computer considers them to be the same object.
Try the following:
man1 = new Man("John"); man2 = new Man("John"); if (man1 == man2) { System.out.println("Equal"); } else { System.out.println("Not equal"); }
You will get βnot equalβ because the computer checks to see if they are exactly the same object, and not just the same.
Each time you use the "new" keyword, you declare a new object, and the computer gives it a unique address.
Try the following:
man1 = new Man("John"); HashMap<Man, Double> myList = new HashMap<>(); myList.put(man1, "5.00"); System.out.print.ln(myList.get(man1));
you will see that now you get "5.00" back because you are actually giving it the exact object, which is the key on the map.
You will need to manually determine how you decide that the two βmenβ are equal if you want the behavior to work that way. You might be better off using the full name as the key, as this will usually be unique and work less for you.
source share