Skip to content

Commit 100441e

Browse files
committed
feat: add contains() method to DynamicArray
1 parent 504b528 commit 100441e

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,21 @@ public int getSize() {
126126
public boolean isEmpty() {
127127
return size == 0;
128128
}
129+
/**
130+
* Checks whether the array contains the specified element.
131+
*
132+
* @param element the element to check for
133+
* @return true if the array contains the specified element, false otherwise
134+
*/
135+
public boolean contains(final E element) {
136+
for (int i = 0; i < size; i++) {
137+
if (Objects.equals(elements[i], element)) {
138+
return true;
139+
}
140+
}
141+
return false;
142+
}
143+
129144

130145
/**
131146
* Returns a sequential stream with this collection as its source.

src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,4 +255,23 @@ public void testCapacityDoubling() {
255255
assertEquals(3, array.getSize());
256256
assertEquals("Charlie", array.get(2));
257257
}
258+
@Test
259+
public void testContains() {
260+
DynamicArray<Integer> array = new DynamicArray<>();
261+
array.add(1);
262+
array.add(2);
263+
array.add(3);
264+
265+
assertTrue(array.contains(2));
266+
assertFalse(array.contains(5));
267+
}
268+
269+
@Test
270+
public void testContainsWithNull() {
271+
DynamicArray<String> array = new DynamicArray<>();
272+
array.add(null);
273+
274+
assertTrue(array.contains(null));
275+
}
276+
258277
}

0 commit comments

Comments
 (0)