Why doesn't java.util.HashSet have a get(Object o) method?

后端 未结 11 2269
暖寄归人
暖寄归人 2020-12-07 18:39

I\'ve seen other questions about getting objects from Set\'s based on index value and I understand why that is not possible. But I haven\'t been able to find a

11条回答
  •  臣服心动
    2020-12-07 19:07

    A Set is a Collection of objects which treats a.equals(b) == true as duplicates, so it doesn't make sense to try to get the same object you already have.

    If you are trying to get(Object) from a collection, a Map is likely to be more appropriate.

    What you should write is

    Map map = new LinkedHashMap<>();
    
    map.put("1", "Number 1");
    map.put("2", null);
    String description = map.get("1");
    

    if an object is not in the set (based on equals), add it, if it is in the set (based on equals) give me the set's instance of that object

    In the unlikely event you need this you can use a Map.

    Map map = // LinkedHashMap or ConcurrentHashMap
    
    Bar bar1 = new Bar(1);
    map.put(bar1, bar1);
    
    Bar bar1a = map.get(new Bar(1));
    

提交回复
热议问题