As set entries are distinguished only by a subset of properties (hashCode()
+ equals()
), there is sometimes a need to operate on original object contained in a set, which is not possible with java.util.Set
. The only alternative I came up with is: Map<T, T>
- not a very concise solution.
Are there any other alternatives in collections framework? Requirements are: O(1) fetch time and no duplicates based on hashCode() + equals()
result.
As java set doesn't provide get method, I need to iterate over the set in my code and update the name when I find the equal object (i.e. when ID matches). If you had get method, this code could have been shortened.
HashSet can not guarantee insertion order so no point in get method. What are you missing is implementing equals and use contains() which will iterate and find the object.
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
If one more O(1) operation is not problem, you can simulate absenting method get(Object)
with pair of methods set.remove(Object)
and set.add(Object)
. Otherwise, I would use Map<T,T>
as you mentioned or simple wrapper class with underlying map.
EDIT: The reason why Set
doesn't contain get(Object)
is that you don't need to return object which you know. You just need to check, if your object is contained in set or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With