This commit is contained in:
Joel Dice
2007-08-20 18:24:54 -06:00
parent e2f3e80bdf
commit 27c8511c5e
6 changed files with 56 additions and 34 deletions

View File

@ -1,24 +1,30 @@
package java.util;
public class ArrayList<T> implements List<T> {
private static final int MinimumCapacity = 16;
private Object[] array;
private int size;
public ArrayList(int capacity) {
if (capacity != 0) {
array = new Object[capacity];
}
resize(capacity);
}
public ArrayList() {
this(0);
}
private void grow() {
if (array == null || size >= array.length) {
resize(array == null ? MinimumCapacity : array.length * 2);
}
}
private void resize() {
if (array == null || size >= array.length - 1) {
resize(array == null ? 16 : array.length * 2);
} else if (size <= array.length / 3) {
private void shrink() {
if (array.length / 2 >= MinimumCapacity && size <= array.length / 3) {
resize(array.length / 2);
} else if (size == 0) {
resize(0);
}
}
@ -55,8 +61,9 @@ public class ArrayList<T> implements List<T> {
}
public boolean add(T element) {
resize();
array[size++] = element;
++ size;
grow();
array[size - 1] = element;
return true;
}
@ -78,7 +85,7 @@ public class ArrayList<T> implements List<T> {
}
-- size;
resize();
shrink();
return v;
}

View File

@ -1,6 +1,8 @@
package java.util;
public class HashMap<K, V> implements Map<K, V> {
private static final int MinimumCapacity = 16;
private int size;
private Cell[] array;
private final Helper helper;
@ -46,11 +48,17 @@ public class HashMap<K, V> implements Map<K, V> {
return size;
}
private void resize() {
private void grow() {
if (array == null || size >= array.length * 2) {
resize(array == null ? 16 : array.length * 2);
} else if (size <= array.length / 3) {
resize(array == null ? MinimumCapacity : array.length * 2);
}
}
private void shrink() {
if (array.length / 2 >= MinimumCapacity && size <= array.length / 3) {
resize(array.length / 2);
} else if (size == 0) {
resize(0);
}
}
@ -94,7 +102,7 @@ public class HashMap<K, V> implements Map<K, V> {
private void insert(Cell<K, V> cell) {
++ size;
resize();
grow();
int index = cell.hashCode() & (array.length - 1);
cell.setNext(array[index]);
@ -116,7 +124,7 @@ public class HashMap<K, V> implements Map<K, V> {
}
}
resize();
shrink();
}
private Cell<K, V> putCell(K key, V value) {
@ -161,7 +169,7 @@ public class HashMap<K, V> implements Map<K, V> {
}
}
resize();
shrink();
}
return old;
}