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