What is an efficient and elegant way to add a single element to an immutable set?

后端 未结 7 757
谎友^
谎友^ 2020-12-29 21:40

I have an immutable set (cast as a Set) that potentially contains many elements. I need a Collection that contains the elements from that set plu

7条回答
  •  有刺的猬
    2020-12-29 22:16

    You have three options.

    • Use a mutable set.
    • Check the element isn't already present, if not create a copy of the set and add an element.
    • Create a wrapper set which includes the previous set and the element.

    Sometimes a BitSet is a better choice than Set depending on the distribution of your values.

提交回复
热议问题