This has been buzzing me for quite some time now. It's basically that whenever I want to store my own set of objects (I called it MyObject here) as keys in the map, I can't get the keyvalue unless I have the same exact object somewhere saved in my class. Even though I tried to override the equals method in MyObject, where it usually returned true when comparing 2 objects with the same values, nothing changed.
Just to give you a demonstration of what I mean:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(2, 3);
System.out.println(map.get(2)));
Now, as you'd probably expect, it searches the map for the Integer-object 2 and then prints out 3. If the integer doesn't exist, it prints null. So far so good.
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(new String("hi"), 3);
System.out.println(map.get(new String("hi")));
This one works also as expected. We're just getting the value for the key "hi".
Map<MyObject, Integer> map = new HashMap<MyObject, Integer>();
map.put(new MyObject(), 3);
System.out.println(map.get(new MyObject()));
Even though, there isn't technically a difference between "new MyObject()" and "new MyObject()", it returns null anyway, unless I saved the new MyObject as an instance in my class and used that instance as the parameter for the get-method.
Contrary to my MyObject, the map easily grabbed the key values, if the keys were Strings or Integers. Are those types just privileged or is there a way to tell the map: "Hey, the newly created object is similar with that one in that list"? How does a map compare objects?