Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Set of Bytes

Tags:

java

Can anyone help me to know how can I have a "Set" of Bytes in Java? Thank you

like image 281
Red Lion Avatar asked Sep 05 '26 12:09

Red Lion


2 Answers

Set<Byte> option from the Java Collections Framework

If you want to harness the Java Collections Framework, you can have a java.util.Set<Byte>. Unfortunately Java generics doesn't work with primitive. java.lang.Byte is the box type for byte. Perhaps an implementation that you can use is a TreeSet; it is a SortedSet, so you can sort the (boxed) byte by their natural ordering.

See also

  • Java Language Guide/Autoboxing
  • Java Tutorials/Collections Framework

Related questions

  • Generics over objects only? (yes, unfortunately)

BitSet option for performance

Another option is a java.util.BitSet. This is a very time and space efficient data structure that implements set representation using bits, i.e. an int i is "in the set" if bit i is set.

BitSet is not part of the Java Collections Framework.

Here's an example usage:

    BitSet bytes = new BitSet();

    bytes.set(3);
    bytes.set(7);
    bytes.set(11);
    bytes.set(11);
    bytes.set(1000);

    System.out.println(bytes);
    // {3, 7, 11, 1000}

    System.out.println(bytes.cardinality()); // 4

    System.out.println(bytes.get(10)); // false

Note that you may set bits that are out of the byte range.

In fact, you can't directly set all bits in the byte range, since byte is a signed datatype in Java. You can use bit masking to convert any byte to an int in the 0..255 range as follows:

    byte b = -1;
    // bytes.set(b); // throws IndexOutOfBoundsException
    bytes.set(b & 0xFF);
    System.out.println(bytes);
    // {3, 7, 11, 255, 1000}

You can then iterate over all byte in the set as follows:

    for (int i = -1; (i = bytes.nextSetBit(i + 1)) != -1; ) {
        byte b = (byte) i;
        System.out.println(b);
    }
    // 3, 7, 11, -1, -24

Note that because of the byte [-128,127] to int [0,255] mapping, negatives come after positives. BitSet also facilitates efficient set operations against other BitSet, like or, and, xor, equals, intersects, etc.

Related questions

  • James Gosling’s explanation of why Java’s byte is signed
    • The range of Java's byte is -128..127, not 0..255.
like image 142
polygenelubricants Avatar answered Sep 08 '26 02:09

polygenelubricants


As polygenelubricants says, you can have a Set<Byte>. Another simple alternative would be to have:

boolean[] byteSet = new boolean[256];

This would be very efficient to check or set each value - and iterating over the set of values would only take 256 iterations anyway :)

like image 30
Jon Skeet Avatar answered Sep 08 '26 03:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!