What is the reason for BitSet's size() method?

后端 未结 4 1324
青春惊慌失措
青春惊慌失措 2021-02-07 12:06

Is there a use case for the size() method on the java.util.BitSet class?

I mean - the JavaDoc clearly says it\'s implementation dependant, it returns the size of the int

4条回答
  •  花落未央
    2021-02-07 12:58

    I realized BitSet was introduced in Java 1.0 while the Collections framework with most of the classes we use was introduced in Java 1.2.

    Correct.

    So basically it seems to me that size() is kept because of legacy reasons and there's no real use for it.

    Yes, pretty much.

    The other "size" method is length() which gives you the largest index at which a bit is set. From a logical perspective, length() is more useful than size() ... but length() was only introduced in Java 1.2.

    The only (hypothetical) use-case I can think of where size() might be better than length() is when:

    • you are trying to establish a "fence post" for an iteration of the bits in the set, and
    • it is highly likely that you will stop iterating well before the end, and
    • it doesn't matter is you go a little bit beyond the last bit that is set.

    In that case, size() is arguably better than length() because it is a cheaper call. (Look at the source code ...) But that's pretty marginal.

    (I guess, another use-case along similar lines is when you are creating a new BitSet and preallocating it based on the size() of an existing BitSet. Again, the difference is marginal.)

    But you are right about compatibility. It is clear that they could not either get rid of size() or change its semantics without creating compatibility problems. So they presumably decided to leave it alone. (Indeed, they didn't even see the need to deprecate it. The "harm" in having a not-particularly-useful method in the API is minimal.)

提交回复
热议问题