java - Why won't my HashSet allow me to add two of the same instance, if their equals() says they're false? -
the documentation hashset.add
says
adds specified element set if not present. more formally, adds specified element e set if set contains no element e2 such (e==null ? e2==null : e.equals(e2)). if set contains element, call leaves set unchanged , returns false.
since code below return false e.equals(e2)
, i'd expect let me add same instance twice. set contains instance once. can explain why?
package com.sandbox; import java.util.hashset; import java.util.set; public class sandbox { public static void main(string[] args) { set<a> = new hashset<a>(); oneinstance = new a(); system.out.println(oneinstance.equals(oneinstance)); //this prints false as.add(oneinstance); as.add(oneinstance); system.out.println(as.size()); //this prints 1, i'd expect print 2 since system.out printed false } private static class { private integer key; @override public boolean equals(object o) { if (!(o instanceof a)) { return false; } a = (a) o; if (this.key == null || a.key == null) { return false; //the key null, should return false } if (key != null ? !key.equals(a.key) : a.key != null) { return false; } return true; } @override public int hashcode() { return key != null ? key.hashcode() : 0; } } }
hashset (really hashmap under hood) has "optimization" in checks object reference equality before calling equals()
method. since putting same instance in twice, considered equal though equals()
method not agree.
relevant line hashmap.put():
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
Comments
Post a Comment