Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do maps check keys?
    primarykey
    data
    text
    <p>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.</p> <p>Just to give you a demonstration of what I mean:</p> <hr> <pre><code>Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;(); map.put(2, 3); System.out.println(map.get(2))); </code></pre> <p>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.</p> <hr> <pre><code>Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;(); map.put(new String("hi"), 3); System.out.println(map.get(new String("hi"))); </code></pre> <p>This one works also as expected. We're just getting the value for the key "hi".</p> <hr> <pre><code>Map&lt;MyObject, Integer&gt; map = new HashMap&lt;MyObject, Integer&gt;(); map.put(new MyObject(), 3); System.out.println(map.get(new MyObject())); </code></pre> <p>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.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload