Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java.util.Set does not contain value getter? Are there alternatives to it?

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.

like image 932
Marcin Avatar asked Jul 11 '13 13:07

Marcin


People also ask

Does set have get method in Java?

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.

Why HashSet has no get method?

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.

Is set a collection Java?

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.


1 Answers

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.

like image 155
matoni Avatar answered Oct 20 '22 22:10

matoni