I understand that only one instance of any object according to .equals() is allowed in a Set and that you shouldn't "need to" get an object from the Set if you already have an equivalent object, but I would still like to have a .get() method that returns the actual instance of the object in the Set (or null) given an equivalent object as a parameter.
Any ideas/theories as to why it was designed like this?
I usually have to hack around this by using a Map and making the key and the value same, or something like that.
EDIT: I don't think people understand my question so far. I want the exact object instance that is already in the set, not a possibly different object instance where .equals() returns true.
As to why I would want this behavior, typically .equals() does not take into account all the properties of the object. I want to provide some dummy lookup object and get back the actual object instance in the Set.
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.
Check if Set Contains Element You can check if a Java Set contains a given element (object) by calling the contains() method. Here is an example of checking if a Java Set contains a given element: Set<String> set = new HashSet<>(); set. add("123"); set.
util. *; public class classA { public classA(classB x, classB y) { Set<classB> setElements = new HashSet<classB>(); setElements. add(x); setElements. add(y); public set<classB> getElements() { return setElements; //THIS IS WHERE MY ERROR IS.
While the purity argument does make the method get(Object)
suspect, the underlying intent is not moot.
There are various class and interface families that slightly redefine equals(Object)
. One need look no further than the collections interfaces. For example, an ArrayList and a LinkedList can be equal; their respective contents merely need to be the same and in the same order.
Consequently, there are very good reasons for finding the matching element in a set. Perhaps a clearer way of indicating intent is to have a method like
public interface Collection<E> extends ... { ... public E findMatch(Object o) throws UnsupportedOperationException; ... }
Note that this API has value broader that within Set.
As to the question itself, I don't have any theory as to why such an operation was omitted. I will say that the minimal spanning set argument does not hold, because many operations defined in the collections APIs are motivated by convenience and efficiency.
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