Repository navigation
datastructure.array: generic DynamicArray<T> #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
diegourban
wants to merge
3
commits into
master
Choose a base branch
from
int-dynamic-array
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
130 changes: 130 additions & 0 deletions
130
src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| package io.github.diegourban.algorithms.datastructure.array; | ||
|
|
||
| /** | ||
| * A growable list of values of any type, backed by an array that is replaced by a larger or smaller copy as values | ||
| * are added and removed. | ||
| * <p> | ||
| * Growth policy: the capacity starts at {@value #INITIAL_CAPACITY}, doubles when an element is added to a full array, | ||
| * and halves when a removal leaves the array less than a quarter full, but never drops below | ||
| * {@value #INITIAL_CAPACITY}. Shrinking at a quarter (not a half) keeps alternating appends and removals from resizing | ||
| * every time, so every operation is amortised O(1) apart from the index shifts of {@link #pop(int)}. | ||
| * <p> | ||
| * The backing store is an {@code Object[]} cast to {@code T[]}, because Java cannot create an array of a type | ||
| * parameter; the cast is safe because only {@code T} values are ever stored in it. | ||
| * | ||
| * @param <T> the type of the stored values | ||
| */ | ||
| public class DynamicArray<T> { | ||
|
|
||
| /** | ||
| * The capacity of a new array, and the smallest capacity it ever shrinks to. | ||
| */ | ||
| public static final int INITIAL_CAPACITY = 10; | ||
|
|
||
| private int size; | ||
| private int capacity; | ||
| private T[] fixedArray; | ||
|
|
||
| /** | ||
| * Creates an empty array with capacity {@value #INITIAL_CAPACITY}. | ||
| */ | ||
| public DynamicArray() { | ||
| this.capacity = INITIAL_CAPACITY; | ||
| this.size = 0; | ||
| this.fixedArray = (T[]) new Object[capacity]; | ||
| } | ||
|
|
||
| /** | ||
| * Appends a value at the end, doubling the capacity first if the array is full. | ||
| * | ||
| * @param value the value to append | ||
| */ | ||
| public void append(final T value) { | ||
| if (this.size == this.capacity) { | ||
| this.resize(this.capacity * 2); | ||
| } | ||
| this.fixedArray[this.size] = value; | ||
| this.size += 1; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the value at the given index. | ||
| * | ||
| * @param index the zero-based index, from {@code 0} to {@code size() - 1} | ||
| * @return the value at {@code index} | ||
| * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} | ||
| */ | ||
| public T get(final int index) { | ||
| if (index < 0 || index >= this.size) { | ||
| throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); | ||
| } | ||
| return this.fixedArray[index]; | ||
| } | ||
|
|
||
| /** | ||
| * Replaces the value at the given index. | ||
| * | ||
| * @param index the zero-based index, from {@code 0} to {@code size() - 1} | ||
| * @param value the new value | ||
| * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} | ||
| */ | ||
| public void set(final int index, final T value) { | ||
| if (index < 0 || index >= this.size) { | ||
| throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); | ||
| } | ||
| this.fixedArray[index] = value; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the number of stored values. | ||
| * | ||
| * @return the number of values | ||
| */ | ||
| public int size() { | ||
| return this.size; | ||
| } | ||
|
|
||
| /** | ||
| * Removes the last value, then halves the capacity if the array is left less than a quarter full (never below | ||
| * {@value #INITIAL_CAPACITY}). | ||
| * | ||
| * @throws IndexOutOfBoundsException if the array is empty | ||
| */ | ||
| public void popBack() { | ||
| if (this.size == 0) { | ||
| throw new ArrayIndexOutOfBoundsException("Index: 0, Size: " + this.size); | ||
| } | ||
| this.size -= 1; | ||
| this.fixedArray[this.size] = null; // release the removed value so it can be garbage-collected | ||
| if ((double) this.size / this.capacity < 0.25 && this.capacity > INITIAL_CAPACITY) { | ||
| this.resize(this.capacity / 2); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Removes the value at the given index, shifting all later values one position left, then shrinks like | ||
| * {@link #popBack()}. | ||
| * | ||
| * @param index the zero-based index, from {@code 0} to {@code size() - 1} | ||
| * @return the removed value | ||
| * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} | ||
| */ | ||
| public T pop(final int index) { | ||
| if (index < 0 || index >= this.size) { | ||
| throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); | ||
| } | ||
| final T value = this.fixedArray[index]; | ||
| for (int i = index; i < this.size - 1; i++) { | ||
| this.fixedArray[i] = this.fixedArray[i + 1]; | ||
| } | ||
| this.popBack(); | ||
| return value; | ||
| } | ||
|
|
||
| private void resize(final int newCapacity) { | ||
| final T[] newArray = (T[]) new Object[newCapacity]; | ||
| System.arraycopy(this.fixedArray, 0, newArray, 0, this.size); | ||
| this.fixedArray = newArray; | ||
| this.capacity = newCapacity; | ||
| } | ||
| } | ||
92 changes: 92 additions & 0 deletions
92
...st/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayPropertyTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package io.github.diegourban.algorithms.datastructure.array; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import net.jqwik.api.Arbitraries; | ||
| import net.jqwik.api.Arbitrary; | ||
| import net.jqwik.api.Combinators; | ||
| import net.jqwik.api.ForAll; | ||
| import net.jqwik.api.Property; | ||
| import net.jqwik.api.Provide; | ||
| import net.jqwik.api.Tuple; | ||
|
|
||
| /** | ||
| * Model-based check: any sequence of operations leaves {@link DynamicArray} holding exactly what a | ||
| * {@link java.util.ArrayList} holds after the same operations. Indexes are generated as raw numbers and wrapped into | ||
| * the valid range for the current size, so every operation is legal and long sequences grow and shrink the array | ||
| * across several resizes. | ||
| */ | ||
| class DynamicArrayPropertyTest { | ||
|
|
||
| sealed interface Operation permits Append, Set, PopBack, Pop {} | ||
|
|
||
| record Append(int value) implements Operation {} | ||
|
|
||
| record Set(int rawIndex, int value) implements Operation {} | ||
|
|
||
| record PopBack() implements Operation {} | ||
|
|
||
| record Pop(int rawIndex) implements Operation {} | ||
|
|
||
| @Provide | ||
| Arbitrary<List<Operation>> operationSequences() { | ||
| return operations().list().ofMaxSize(200); | ||
| } | ||
|
|
||
| private static Arbitrary<Operation> operations() { | ||
| final Arbitrary<Integer> values = Arbitraries.integers(); | ||
| final Arbitrary<Integer> rawIndexes = Arbitraries.integers().greaterOrEqual(0); | ||
| return Arbitraries.frequencyOf( | ||
| Tuple.of(5, values.map(Append::new)), | ||
| Tuple.of(2, Combinators.combine(rawIndexes, values).as(Set::new)), | ||
| Tuple.of(2, Arbitraries.just(new PopBack())), | ||
| Tuple.of(2, rawIndexes.map(Pop::new))); | ||
| } | ||
|
|
||
| @Property | ||
| void behavesLikeAnArrayList(@ForAll("operationSequences") final List<Operation> operations) { | ||
| final DynamicArray<Integer> array = new DynamicArray<>(); | ||
| final List<Integer> model = new ArrayList<>(); | ||
|
|
||
| for (final Operation operation : operations) { | ||
| apply(operation, array, model); | ||
|
|
||
| assertThat(array.size()).isEqualTo(model.size()); | ||
| for (int i = 0; i < model.size(); i++) { | ||
| assertThat(array.get(i)) | ||
| .as("value at %d after %s", i, operation) | ||
| .isEqualTo(model.get(i)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static void apply(final Operation operation, final DynamicArray<Integer> array, final List<Integer> model) { | ||
| switch (operation) { | ||
| case Append(final int value) -> { | ||
| array.append(value); | ||
| model.add(value); | ||
| } | ||
| case Set(final int rawIndex, final int value) -> { | ||
| if (!model.isEmpty()) { | ||
| final int index = rawIndex % model.size(); | ||
| array.set(index, value); | ||
| model.set(index, value); | ||
| } | ||
| } | ||
| case PopBack() -> { | ||
| if (!model.isEmpty()) { | ||
| array.popBack(); | ||
| model.removeLast(); | ||
| } | ||
| } | ||
| case Pop(final int rawIndex) -> { | ||
| if (!model.isEmpty()) { | ||
| final int index = rawIndex % model.size(); | ||
| assertThat(array.pop(index)).isEqualTo(model.remove(index)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
160 changes: 160 additions & 0 deletions
160
src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| package io.github.diegourban.algorithms.datastructure.array; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.assertj.core.api.Assertions.assertThatExceptionOfType; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| class DynamicArrayTest { | ||
|
|
||
| @SafeVarargs | ||
| private static <T> DynamicArray<T> of(final T... values) { | ||
| final DynamicArray<T> array = new DynamicArray<>(); | ||
| for (final T value : values) { | ||
| array.append(value); | ||
| } | ||
| return array; | ||
| } | ||
|
|
||
| private static <T> List<T> contents(final DynamicArray<T> array) { | ||
| final List<T> values = new ArrayList<>(); | ||
| for (int i = 0; i < array.size(); i++) { | ||
| values.add(array.get(i)); | ||
| } | ||
| return values; | ||
| } | ||
|
|
||
| @Test | ||
| void startsEmpty() { | ||
| final DynamicArray<Integer> array = new DynamicArray<>(); | ||
|
|
||
| assertThat(array.size()).isZero(); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(0)); | ||
| } | ||
|
|
||
| @Test | ||
| void appendsInOrder() { | ||
| final DynamicArray<Integer> array = of(3, 1, 2); | ||
|
|
||
| assertThat(array.size()).isEqualTo(3); | ||
| assertThat(contents(array)).containsExactly(3, 1, 2); | ||
| } | ||
|
|
||
| @Test | ||
| void holdsValuesOfAnyType() { | ||
| final DynamicArray<String> array = of("a", "b"); | ||
|
|
||
| array.set(0, "z"); | ||
| array.append(null); | ||
|
|
||
| assertThat(contents(array)).containsExactly("z", "b", null); | ||
| assertThat(array.pop(1)).isEqualTo("b"); | ||
| } | ||
|
|
||
| @Test | ||
| void setReplacesTheValueAtAnIndex() { | ||
| final DynamicArray<Integer> array = of(1, 2, 3); | ||
|
|
||
| array.set(1, 20); | ||
|
|
||
| assertThat(contents(array)).containsExactly(1, 20, 3); | ||
| } | ||
|
|
||
| @Test | ||
| void popBackRemovesTheLastValue() { | ||
| final DynamicArray<Integer> array = of(1, 2, 3); | ||
|
|
||
| array.popBack(); | ||
|
|
||
| assertThat(contents(array)).containsExactly(1, 2); | ||
| } | ||
|
|
||
| @Test | ||
| void popRemovesTheValueAtAnIndexShiftingLaterOnesAndReturnsIt() { | ||
| final DynamicArray<Integer> array = of(1, 2, 3, 4); | ||
|
|
||
| assertThat(array.pop(1)).isEqualTo(2); | ||
| assertThat(contents(array)).containsExactly(1, 3, 4); | ||
|
|
||
| assertThat(array.pop(2)).isEqualTo(4); | ||
| assertThat(array.pop(0)).isEqualTo(1); | ||
| assertThat(contents(array)).containsExactly(3); | ||
| } | ||
|
|
||
| @Test | ||
| void keepsEveryValueWhileGrowingPastTheInitialCapacity() { | ||
| final DynamicArray<Integer> array = new DynamicArray<>(); | ||
| for (int i = 0; i < 1000; i++) { | ||
| array.append(i); | ||
| } | ||
|
|
||
| assertThat(array.size()).isEqualTo(1000); | ||
| for (int i = 0; i < 1000; i++) { | ||
| assertThat(array.get(i)).isEqualTo(i); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void keepsTheRemainingValuesWhileShrinking() { | ||
| final DynamicArray<Integer> array = new DynamicArray<>(); | ||
| for (int i = 0; i < 1000; i++) { | ||
| array.append(i); | ||
| } | ||
|
|
||
| while (array.size() > 3) { | ||
| array.popBack(); | ||
| } | ||
|
|
||
| assertThat(contents(array)).containsExactly(0, 1, 2); | ||
| array.append(99); | ||
| assertThat(contents(array)).containsExactly(0, 1, 2, 99); | ||
| } | ||
|
|
||
| @Test | ||
| void canBeEmptiedAndReused() { | ||
| final DynamicArray<Integer> array = of(1, 2); | ||
|
|
||
| array.popBack(); | ||
| array.pop(0); | ||
| assertThat(array.size()).isZero(); | ||
|
|
||
| array.append(7); | ||
| assertThat(contents(array)).containsExactly(7); | ||
| } | ||
|
|
||
| @Test | ||
| void rejectsIndexesOutsideTheStoredValues() { | ||
| final DynamicArray<Integer> array = of(1, 2); | ||
|
|
||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(2)); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(-1)); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.set(2, 0)); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.set(-1, 0)); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.pop(2)); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.pop(-1)); | ||
| assertThat(contents(array)).containsExactly(1, 2); | ||
| } | ||
|
|
||
| @Test | ||
| void rejectsPoppingFromAnEmptyArray() { | ||
| final DynamicArray<Integer> array = new DynamicArray<>(); | ||
|
|
||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(array::popBack); | ||
| assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.pop(0)); | ||
| } | ||
|
|
||
| @Test | ||
| void popBackFromAFullArray() { | ||
| final DynamicArray<Integer> array = new DynamicArray<>(); | ||
| for (int i = 0; i < DynamicArray.INITIAL_CAPACITY; i++) { | ||
| array.append(i); | ||
| } | ||
|
|
||
| array.popBack(); | ||
|
|
||
| assertThat(array.size()).isEqualTo(DynamicArray.INITIAL_CAPACITY - 1); | ||
| assertThat(array.get(array.size() - 1)).isEqualTo(DynamicArray.INITIAL_CAPACITY - 2); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 MEDIUM RISK
Capacity growth is not overflow-safe: doubling a sufficiently large capacity can wrap to a negative value and cause
NegativeArraySizeExceptionon the next append. Guard the calculation, cap it at the maximum supported array size, and report exhaustion when no further growth is possible.TIPReact 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.