Note that there are some explanatory texts on larger screens.

plurals
  1. POJava HashMap cannot find key from within ListDataListener event
    primarykey
    data
    text
    <p>Can someone explain why the HashMap acts like it does in this example:<br> Simple test that checks a hashmap for a key. Once in the constructor and once in ListDataListener intervallAdded method.</p> <pre><code>import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import com.jgoodies.common.collect.ArrayListModel; public class Test1 { private final Listener listener = new Listener(); private final Map&lt;List&lt;?&gt;, Object&gt; parentByCollection = new HashMap&lt;List&lt;?&gt;, Object&gt;(); public Test1(){ ArrayListModel&lt;Object&gt; list = new ArrayListModel&lt;Object&gt;(); list.addListDataListener(listener); parentByCollection.put(list, new Integer(10)); // Test containsKey locally System.out.println("Item exists (locally):" + parentByCollection.containsKey(list)); // Test containsKey via ListDataListener list.add(new Integer(20)); } /** * @param args */ public static void main(String[] args) { new Test1(); } public class Listener implements ListDataListener{ @Override public void intervalAdded(ListDataEvent e) { List&lt;?&gt; itemSource = (List&lt;?&gt;)e.getSource(); System.out.println("Item exists (listener):" + parentByCollection.containsKey(itemSource)); } @Override public void intervalRemoved(ListDataEvent e) { } @Override public void contentsChanged(ListDataEvent e) { } } } </code></pre> <p>Why does the hashmap return false from the event but true from constructor when using containsKey? Is there some java-generics "magic" I don't know about here? </p> <p>Edit:</p> <p>Just found that ArrayList's (which ArrayListModel extends) hashCode method assembles its hashcode from all its elements. Which means the hashCode changes with the items in the list. So storing a ArrayList in a HashMap is not a good idea.</p> <p>How can I solve this? Store the collections in a holder/container object instead?</p>
    singulars
    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.
    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