Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
Raffi Khatchadourian Avatar asked Jan 24 '17 20:01

Raffi Khatchadourian


People also ask

How does a BitSet work?

Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1 . All bits are initially false .

How does BitSet work in Java?

The BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4.

How is BitSet implemented in C++?

Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.

Why do we use BitSet?

A BitSet is a very efficient for a set of non-negative integers within a (not too large) range. Much more efficient than arrays and hash maps. An EnumSet is implemented the same way as a BitSet .


3 Answers

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.

like image 174
Andy Turner Avatar answered Nov 11 '22 04:11

Andy Turner


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.

like image 32
M A Avatar answered Nov 11 '22 04:11

M A


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.

like image 20
Fabien Benoit-Koch Avatar answered Nov 11 '22 03:11

Fabien Benoit-Koch