Skip to content

Commit

Permalink
Fixed bug in DynamicArray last element - credit goes to Andre Luis Gomes
Browse files Browse the repository at this point in the history
  • Loading branch information
jrasmusson committed Mar 23, 2020
1 parent 6178112 commit f1fa7e5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 25 deletions.
10 changes: 7 additions & 3 deletions src/main/java/datastructures/DynamicArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,16 @@ public void delete(int index) {
for (int j = index; j < size - 1; j++) {
data[j] = data[j + 1];
}
size--;

// Clear if last element in array
if (index == size) {
// Clear last element of array

if (index == size) { // index is last element
data[index] = null;
} else {
data[size - 1] = null; // index not last element
}

size--;
}

public boolean isEmpty() {
Expand Down
24 changes: 2 additions & 22 deletions src/test/java/datastructures/DynamicArrayTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public void DeleteFirst() {
Assert.assertEquals(2, array.size());
Assert.assertEquals("b", array.get(0));
Assert.assertEquals("c", array.get(1));
Assert.assertEquals(null, array.get(2));
}

@Test
Expand All @@ -58,6 +59,7 @@ public void DeleteMiddle() {
Assert.assertEquals(2, array.size());
Assert.assertEquals("a", array.get(0));
Assert.assertEquals("c", array.get(1));
Assert.assertEquals(null, array.get(2));
}

@Test
Expand All @@ -74,28 +76,6 @@ public void DeleteLast() {
Assert.assertEquals(null, array.get(2));
}

@Test
public void DeleteLastArraySize1() {
array.add("a");

array.delete(0);

Assert.assertEquals(0, array.size());
Assert.assertEquals(null, array.get(0));
}

@Test
public void DeleteLastArraySize2() {
array.add("a");
array.add("b");

array.delete(1);

Assert.assertEquals(1, array.size());
Assert.assertEquals("a", array.get(0));
Assert.assertEquals(null, array.get(1));
}

@Test
public void isEmpty() {
Assert.assertTrue(array.isEmpty());
Expand Down

0 comments on commit f1fa7e5

Please sign in to comment.