Skip to content

Commit fe71775

Browse files
add remove target function
1 parent de03928 commit fe71775

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

‎src/main/java/com/examplehub/datastructures/array/ArrayList.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,24 @@ public E remove(int index) {
134134
return removed;
135135
}
136136

137+
/**
138+
* Remove all given elements.
139+
*
140+
* @param target the target element to be removed.
141+
* @return the number removed.
142+
*/
143+
public int remove(E target) {
144+
int count = 0;
145+
for (int i = 0; i < size; ++i) {
146+
if (!elements[i].equals(target)) {
147+
elements[count++] = elements[i];
148+
}
149+
}
150+
int removedCount = size - count;
151+
size = count;
152+
return removedCount;
153+
}
154+
137155
/**
138156
* Clear all elements in this list.
139157
*/

‎src/test/java/com/examplehub/datastructures/array/ArrayListTest.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,18 @@ void testGrow() {
4747
assertEquals(7, arrayList.size());
4848
assertEquals("[1, 2, 3, 4, 5, 6, 7]", arrayList.toString());
4949
}
50+
51+
@Test
52+
void testRemove() {
53+
ArrayList<String> arrayList = new ArrayList<>();
54+
for (int i = 1; i <= 5; i++) {
55+
arrayList.add("" + i);
56+
}
57+
arrayList.add("3");
58+
arrayList.add(2, "3");
59+
assertEquals("[1, 2, 3, 3, 4, 5, 3]", arrayList.toString());
60+
61+
arrayList.remove("3");
62+
assertEquals("[1, 2, 4, 5]", arrayList.toString());
63+
}
5064
}

0 commit comments

Comments
 (0)