简体   繁体   中英

Java HashMap key problems

I am currently making a custom serializer as part of a project, and here I need to serialize references too, meaning that if two fields refer to the same project before serializing, they should too after deserializing.

For this, I am using a HashMap, mapping each object to an ID that I can use as an attribute to each object serialized, while at the same time keeping track on which objects that are already serialized. I have stumbled upon some problems though.

It seems that the java HashMap only checks for equality upon keys and not if they are the same reference. For example, in the following, the variable b ends up true:

HashMap<Object, Integer> map = new HashMap<Object, Integer>();
LinkedList<Object> ll1 = new LinkedList<Object>();
LinkedList<Object> ll2 = new LinkedList<Object>();
map.put(ll1, 5);
boolean b = map.containsKey(ll2);

Some times the result does not make sense at all. Here, b is true too:

HashMap<Object, Integer> map = new HashMap<Object, Integer>();
LinkedList<Object> ll1 = new LinkedList<Object>();
Stack<Object> stack = new Stack<Object>();
map.put(ll1, 5);
boolean b = map.containsKey(stack);

What I want is the ContainsKey-method to not only call the equals method, but also use the '=='-operator checking if the reference is the same. Can I do this without needing to look through the whole keyset?

Thanks in advance

The general contract of the Map interface is that two keys are considered equal if they are both null, or if they are not null and a.equals(b) . It does not use == to compare, unless the key class's implementation of the equals method does this.

The reason your LinkedList and Stack objects are equal is because they both implement the List interface, and the definition of List.equals is that two lists are equal if they have the same size, and contain the same objects in the same order. Since they're both empty, they're "equal".

I believe you're looking for IdentityHashMap . It deliberately violates the contract of the Map interface to use only == , not Object.equals() to compare objects. Likewise, for the hash code it uses System.identityHashCode instead of any overridden Object.hashCode() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM