Skip to content

Commit 775063a

Browse files
author
George Bouroutzoglou
committed
#7: Fix element count int overflow
Element count could overflow due to extensive resizing. It is now possible to add INT_MAX elements without a problem but any more will throw an IllegalStateException. Any more elements cannot be indexed with the List interface anyway.
1 parent da1e2da commit 775063a

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
<groupId>gr.geompokon</groupId>
99
<artifactId>bit-array</artifactId>
10-
<version>1.0.0</version>
10+
<version>1.0.1</version>
1111

1212
<name>BitArray</name>
1313
<description>Java List of Booleans class with reduced memory usage and higher performance</description>

src/main/java/gr/geompokon/bitarray/BitArray.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
* not follow the one bit per entry principle.
5151
* </p>
5252
*
53-
* @version 1.0.0
53+
* @version 1.0.1
5454
* @see java.util.List
5555
* @see java.util.AbstractList
5656
* @see java.util.ArrayList
@@ -430,6 +430,11 @@ private void ensureIndexInRange(int index, int endInclusive) {
430430
* </p>
431431
*/
432432
private void ensureCapacity() {
433+
// check for completely full array
434+
if (elements == Integer.MAX_VALUE) {
435+
throw new IllegalStateException("Cannot insert; array is completely full. Size = " + size());
436+
}
437+
// extend if currently full
433438
if (elements == data.length * BITS_PER_LONG) {
434439
doubleSize();
435440
}
@@ -439,7 +444,10 @@ private void ensureCapacity() {
439444
* Doubles the size of the array.
440445
*/
441446
private void doubleSize() {
442-
resize(2 * elements);
447+
// make sure new element count does not overflow
448+
// we can't index more than Integer.MAX_VALUE elements through the List interface anyway
449+
int newSize = (int) Math.min(2L * elements, Integer.MAX_VALUE);
450+
resize(newSize);
443451
}
444452

445453
/**

0 commit comments

Comments
 (0)