Replacing a HashSet Java member

前端 未结 5 1479
我在风中等你
我在风中等你 2021-01-07 16:47

I have Set of that structure. I do not have duplicates but when I call: set.add(element) -> and there is already exact element I would like the old to be replac

5条回答
  •  时光取名叫无心
    2021-01-07 17:13

    I was working on a problem where I had a set then I wanted to replace/override some of the objects with objects from another set.

    In my case what I ended up doing was creating a new set and putting the overrides in first then adding the current objects second. This works because a set won't replace any existing objects when adding new objects.

    If you have:

    Set currentInfo;
    Set overrides;
    

    Instead of:

    for each override, replace the object in current info
    

    I did:

    Set updated = new HashSet<>();
    updated.addAll(overrides);
    updated.addAll(currentInfo);
    

提交回复
热议问题