Class BitArray
- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractList<Boolean>
-
- io.github.abductcows.bitarray.BitArray
-
- All Implemented Interfaces:
Cloneable,Iterable<Boolean>,Collection<Boolean>,List<Boolean>,RandomAccess
public final class BitArray extends AbstractList<Boolean> implements RandomAccess, Cloneable
Random access List<Boolean> that uses a long primitive array to store its elements. Each element occupies a single bit in its corresponding long
This class is superior to ArrayList in terms of CRUD performance and memory usage. Its limitation is its inability to store
nullvalues.Read only operations such as
get(int)and iterator traversals run at about the same time.Addandremoveat the tail also have similar performance. The most significant gains come from element copy and move operations. This includes random indexaddandremove, array resizes etc. You can find my benchmarks and their results from my machine hereThis class is NOT synchronized. For a synchronized version, use
Collections.SynchronizedList
Caveats
No nulls. As mentioned above, the array will not accept null values, and throw a
NullPointerExceptioninstead.Whole list copies. Note that methods which return a copy of the elements will probably not follow the one bit per entry principle.
SubListandSynchronizedListare safe to use of course.- Version:
- 2.0.0
-
-
Field Summary
Fields Modifier and Type Field Description static intDEFAULT_CAPACITYDefault array capacity in bit entries
-
Constructor Summary
Constructors Constructor Description BitArray()Default constructor; sets initial capacity toDEFAULT_CAPACITYBitArray(int initialCapacity)Initialises the array to store at leastinitialCapacityelements before resizing.BitArray(Collection<? extends Boolean> other)Builds the array from the specified collection in the order specified by its iterator
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidadd(int index, Boolean bit)Inserts the boolean value at the argument index.booleanadd(Boolean bit)Inserts the boolean value at the tail of the array.voidclear()Clears the contents of the array and releases memory used previously.BitArrayclone()Returns a deep copy of this objectintcountOnes()Counts the number oftrueelements in the arrayintcountZeros()Counts the number offalseelements in the arraystatic BitArrayfromString(String stringArray)Constructs the BitArray from the serialized String representation givenBooleanget(int index)Returns the boolean value of the bit at the selected array index.intindexOfNeedle(boolean needle)Finds the index of the first occurrence ofneedleby skipping multiple occurrences of!needleBooleanremove(int index)Removes and returns the element at the specified index.Booleanset(int index, Boolean bit)Sets the value of the element at the specified index to the desired value and returns the old value.intsize()Returns the number of elements in the array.StringtoString()Serializes the array into a string.-
Methods declared in class java.util.AbstractList
addAll, equals, hashCode, indexOf, iterator, lastIndexOf, listIterator, listIterator, subList
-
Methods declared in class java.util.AbstractCollection
addAll, contains, containsAll, isEmpty, remove, removeAll, retainAll, toArray, toArray
-
Methods declared in interface java.util.Collection
parallelStream, removeIf, stream, toArray
-
Methods declared in interface java.util.List
addAll, contains, containsAll, isEmpty, remove, removeAll, replaceAll, retainAll, sort, spliterator, toArray, toArray
-
-
-
-
Field Detail
-
DEFAULT_CAPACITY
public static final int DEFAULT_CAPACITY
Default array capacity in bit entries- See Also:
- Constant Field Values
-
-
Constructor Detail
-
BitArray
public BitArray()
Default constructor; sets initial capacity toDEFAULT_CAPACITY
-
BitArray
public BitArray(int initialCapacity)
Initialises the array to store at leastinitialCapacityelements before resizing.Actual memory size of the array in bits is rounded up to the next multiple of
BITS_PER_LONG.- Parameters:
initialCapacity- initial capacity of the array in bit entries
-
BitArray
public BitArray(Collection<? extends Boolean> other)
Builds the array from the specified collection in the order specified by its iterator- Parameters:
other- the collection supplying the elements- Throws:
NullPointerException- if the collection is null
-
-
Method Detail
-
add
public void add(int index, Boolean bit)Inserts the boolean value at the argument index.- Specified by:
addin interfaceList<Boolean>- Overrides:
addin classAbstractList<Boolean>- Parameters:
index- array index to insert the element inbit- the boolean value to be inserted- Throws:
IndexOutOfBoundsException- if index is out of array insertion boundsIllegalStateException- if array size is Integer.MAX_VALUE at the time of insertion
-
add
public boolean add(Boolean bit)
Inserts the boolean value at the tail of the array.- Specified by:
addin interfaceCollection<Boolean>- Specified by:
addin interfaceList<Boolean>- Overrides:
addin classAbstractList<Boolean>- Parameters:
bit- the boolean value to be inserted- Returns:
- success / failure of the add operation
- Throws:
IllegalStateException- if array size is Integer.MAX_VALUE at the time of insertion
-
get
public Boolean get(int index)
Returns the boolean value of the bit at the selected array index.- Specified by:
getin interfaceList<Boolean>- Specified by:
getin classAbstractList<Boolean>- Parameters:
index- index of the element in the array- Returns:
- boolean value of the bit entry
- Throws:
IndexOutOfBoundsException- if index is out of array bounds
-
set
public Boolean set(int index, Boolean bit)
Sets the value of the element at the specified index to the desired value and returns the old value.- Specified by:
setin interfaceList<Boolean>- Overrides:
setin classAbstractList<Boolean>- Parameters:
index- index of the array element to be changedbit- the new value of the array element- Returns:
- boolean value of the previous bit at that index
- Throws:
IndexOutOfBoundsException- if index is out of array bounds
-
remove
public Boolean remove(int index)
Removes and returns the element at the specified index.- Specified by:
removein interfaceList<Boolean>- Overrides:
removein classAbstractList<Boolean>- Parameters:
index- index of the element- Returns:
- boolean value of the removed bit
- Throws:
IndexOutOfBoundsException- if index is out of array bounds
-
size
public int size()
Returns the number of elements in the array.- Specified by:
sizein interfaceCollection<Boolean>- Specified by:
sizein interfaceList<Boolean>- Specified by:
sizein classAbstractCollection<Boolean>- Returns:
- number of elements in the array
-
clear
public void clear()
Clears the contents of the array and releases memory used previously.- Specified by:
clearin interfaceCollection<Boolean>- Specified by:
clearin interfaceList<Boolean>- Overrides:
clearin classAbstractList<Boolean>
-
countOnes
public int countOnes()
Counts the number oftrueelements in the array- Returns:
- number of true elements in the array
-
countZeros
public int countZeros()
Counts the number offalseelements in the array- Returns:
- number of false elements in the array
-
indexOfNeedle
public int indexOfNeedle(boolean needle)
Finds the index of the first occurrence ofneedleby skipping multiple occurrences of!needleThis method should be used when
needleis indeed a needle in a haystack of!needleelements. In other cases, it will most likely run slower thanindexOf. It skips ahead of multiples of 64, starting at element 0. Meaning it will skip 0-63, 64-127 etc, using a singlelongcomparison for each.- Parameters:
needle- the boolean element- Returns:
- index of the first occurrence of
needleor -1 if not found
-
clone
@Contract(" -> new") public BitArray clone()Returns a deep copy of this object- Returns:
- deep copy of
this
-
toString
public String toString()
Serializes the array into a string.The string consists of the number of elements in the array and a list of the elements in a human readable format. Exact representation is "Size = SIZE, [(((0 | 1) + ' ')* (0 | 1))?]" where SIZE is a non negative integer and '+' is the concatenation operator. The list of elements consists of opening square brackets ([), zero or more bits (single digit ones or zeros) separated by spaces and closing square brackets.
Examples:
Size = 7, [1 1 1 0 1 1 1]
Size = 4, [0 0 0 0]
Size = 0, []- Overrides:
toStringin classAbstractCollection<Boolean>- Returns:
- String representation of the array and its elements
-
fromString
public static BitArray fromString(String stringArray)
Constructs the BitArray from the serialized String representation given- Parameters:
stringArray- array in String format as returned bytoString()- Returns:
- new BitArray instance with the String array's contents
- Throws:
UnknownFormatConversionException- if string parsing fails
-
-