use a static final empty array if list is empty

This commit is contained in:
2017-09-26 20:10:54 +02:00
parent ab7d554d52
commit d00ab6533d

View File

@@ -18,6 +18,8 @@ public class IntList {
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static final int[] EMPTY_ARRAY = {};
private int[] data;
private int index = 0;
@@ -43,7 +45,7 @@ public class IntList {
"initial capacity must not be negative and not larger than " + MAX_ARRAY_SIZE);
}
data = new int[initialCapacity];
data = initialCapacity > 0 ? new int[initialCapacity] : EMPTY_ARRAY;
}
/**
@@ -283,9 +285,13 @@ public class IntList {
* Call this method to reduce the memory consumption of this list.
*/
public void trim() {
final int[] newData = new int[index];
System.arraycopy(data, 0, newData, 0, index);
data = newData;
if (index == 0) {
data = EMPTY_ARRAY;
} else {
final int[] newData = new int[index];
System.arraycopy(data, 0, newData, 0, index);
data = newData;
}
}
@Override