It should be O(1)
provided the hashcode implementation is reasonably uniform - in the worst case (if everything is hashed to the same bucket) it could be O(N)
.
The trouble is that for this specific example you have precisely that worst possible case - given your either-or equality condition, I can't see a sensible way to implement the hashCode
contract that equal objects must have equal hash codes other than to simply return the same code for every object.
In fact, I don't think you can even have a well-defined equals()
in this case, as your condition is neither symmetric nor transitive
a1(str1 = "A", str2 = "B")
a2(str1 = "B", str2 = "C")
a3(str1 = "C", str2 = "D")
- not symmetric:
a1.equals(a2)
but !a2.equals(a1)
- not transitive:
a1.equals(a2)
and a2.equals(a3)
, but !a1.equals(a3)
.