This commit is contained in:
Huayang Sun
2021-07-15 22:03:07 +08:00
committed by GitHub
parent 2cf749d653
commit d3a6ba2437

View File

@ -11,6 +11,7 @@ import java.util.stream.StreamSupport;
* @param <E> the type that each index of the array will hold
*/
public class DynamicArray<E> implements Iterable<E> {
private static final int DEFAULT_CAPACITY = 16;
private int capacity;
private int size;
@ -27,22 +28,11 @@ public class DynamicArray<E> implements Iterable<E> {
this.elements = new Object[this.capacity];
}
/** No-args constructor */
public DynamicArray() {
this.size = 0;
this.capacity = 10;
this.elements = new Object[this.capacity];
}
/**
* Doubles the capacity of the array
*
* @return int the new capacity of the array
* No-args constructor
*/
public int newCapacity() {
this.capacity *= 2;
// changed from this.capacity <<= 1; now much easier to understand
return this.capacity;
public DynamicArray() {
this(DEFAULT_CAPACITY);
}
/**
@ -52,7 +42,7 @@ public class DynamicArray<E> implements Iterable<E> {
*/
public void add(final E element) {
if (this.size == this.elements.length) {
this.elements = Arrays.copyOf(this.elements, newCapacity());
this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
}
this.elements[this.size] = element;
@ -89,6 +79,8 @@ public class DynamicArray<E> implements Iterable<E> {
final E oldElement = getElement(index);
fastRemove(this.elements, index);
if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity)
this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
return oldElement;
}
@ -128,6 +120,11 @@ public class DynamicArray<E> implements Iterable<E> {
return (E) this.elements[index];
}
private int newCapacity(int capacity) {
this.capacity = capacity;
return this.capacity;
}
/**
* returns a String representation of this object
*