简体   繁体   中英

Why is BitSet not Iterable?

BitSet has a stream() method but it does not implement the Iterable interface like other types that provide this method. Is there a specific reason for this?

None of the methods in Iterable ( foreach , iterator , and spliterator ) is provided in BitSet . There is no stream() method in Iterable .

Furthermore the stream() method of BitSet does not return a stream over the bits of the bit set, but returns a stream over the indices of the bits whose values are set (which is kind of confusing TBH). Therefore, technically speaking there seems to be almost nothing in common with Iterable .

One reason (not the entire reason, maybe) is that Iterable would inefficient, because the bit indexes have to be boxed (*); the stream is able to use primitive ints.

There's an efficient way to iterate the bitset without using Iterable , as described in the Javadoc, so it's not really necessary.


(*) However, for bitsets with size 128 or smaller, boxing would be cheap, as cached boxed instances would be used.

BitSet is not a "true" member of the java collection framework, so technically, no need to implement Collection.iterator() and provide one.

public class BitSet implements Cloneable, java.io.Serializable 

More to the point, both would be ill-fitted togethoer.

BitSet are not generic , unlike java.util.Iterator; BitSet provides ad-hoc methods with special features for side-effects and random addressing, unlike Iterator.

Probably to avoid expensively boxing every bit to a Boolean instance.

Looping over it using its own APIs will avoid all allocations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM