Does Java Trove4J library (or another) have boolean primitive collections?

275 views Asked by At

Google is failing me here... I thought this would be a very simple Q&A, but I cannot find any previous discussion of the matter.

Is there a reason why the Java Trove4J library does not include boolean primitive collections? Example: TByteHashSet exists, but TBooleanHashSet does not.

As a workaround, I can declare two byte constants for true(1) and false(0), but it would be more convenient to have a boolean primitive collection.

2

There are 2 answers

0
Donald Raab On BEST ANSWER

Eclipse Collections has BooleanSet, BooleanList, BooleanStack, BooleanBag and primitive maps with boolean as values. There are both Mutable and Immutable versions. You can find all subinterfaces of BooleanIterable here. Factory classes for the different primitive containers are here.

Here's an example of creating a MutableBooleanList and ImmutableBooleanList using the BooleanLists factory.

MutableBooleanList mutable = BooleanLists.mutable.with(true, false, true, false);
ImmutableBooleanList immutable = BooleanLists.immutable.with(true, false, true, false);
Assert.assertEquals(mutable, immutable);

Note: I am a committer for Eclipse Collections.

3
Rob Eden On

I'm the author, so...

What would be your use case for such a TBooleanHashSet? You could only store four states:

  • empty
  • true
  • false
  • true & false

You could accomplish this easily with an EnumMap and some enum representing your states. Otherwise, the most efficient way would probably be a bit mask.

Anyway, haven't seen a need. (Note: a TBooleanList could make sense, but you could use java.util.BitSet instead.)

If you have a need, please let me know.