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

后端 未结 7 825
谎友^
谎友^ 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:25

    When you want better performance than a full copy, and you have an ordering over elements, you can use an effectively immutable wrapper around a B+ tree to get good incremental set performance.

    Adding an item to a B+ tree requires O(log(n)) time and incremental allocation, not O(n) as you get with ImmutableSet.builder().addAll(...).add(...).build(). This means that building a set from n incremental adds is O(n*log(n)), not O(sqr(n)).

    This answer has a pointer to a jdbm library so it might be worth looking at jdbm:jdbm.

提交回复
热议问题