This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Why does java.util.HashSet have no get (Object O) method? >
Ask questions
I’ve seen other problems with sets getting objects from them based on index values, and I understand why this is not possible. But I can’t find a good explanation for why fetching by object is not allowed, so I’d like to ask.
A HashSet is backed by a HashMap, so getting objects from it should be simple. Now, it seems unnecessary that I have to walk through every item HashSet in the HashSet and test for equality.
I can just use Map but I don’t need a key: value pair, I just need a Set.
For example, say I have foo. Java:
package example;
import java.io.Serializable;
public class Foo implements Serializable {
String _id;
String _description;
public Foo(String id){
this._id = id
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
public boolean equals(Object obj) {
//equals code, checks if id's are equal
}
public int hashCode() {
//hash code calculation}}Copy the code
And Example Java:
package example;
import java.util.HashSet;
public class Example {
public static void main(String[] args){
HashSet<Foo> set = new HashSet<Foo>();
Foo foo1 = new Foo("1");
foo1.setDescription("Number 1");
set.add(foo1);
set.add(new Foo("2"));
//I want to get the object stored in the Set, so I construct a object that is 'equal' to the one I want.
Foo theFoo = set.get(new Foo("1")); //Is there a reason this is not allowed?
System.out.println(theFoo.getDescription); //Should print Number 1}}Copy the code
Is it because the equals method tests for “absolute” equality rather than “logical” equality
(In this case contains(Object O) is sufficient)?
Answer:
Set is an object that is treated as a duplicate Collection object a.equals(b) == true, so it makes no sense to try to get the same object that you already own. If you try to get(Object) from the collection, a Map might be more appropriate. What you should write instead is:
Map<String.String> map = new LinkedHashMap<>();
map.put("1"."Number 1");
map.put("2".null);
String description = map.get("1");
Copy the code
If the object is not in the collection (based on equivalence), please add it (if the object is in the collection (based on equivalence)), please give me the collection instance of the object. In case you need to use this feature, Map can be used.
Map<Bar, Bar> map = // LinkedHashMap or ConcurrentHashMap
Bar bar1 = new Bar(1);
map.put(bar1, bar1);
Bar bar1a = map.get(new Bar(1));
Copy the code
The article translated from Stack Overflow: stackoverflow.com/questions/1…