Skip to content

Commit e48836d

Browse files
committed
Add range checks of index for listIterator() & addAll()
1 parent 949b819 commit e48836d

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/main/java/by/andd3dfx/collections/custom/CustomArrayList.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,9 @@ public ListIterator<T> listIterator() {
154154

155155
@Override
156156
public ListIterator<T> listIterator(int index) {
157+
if (index < 0 || index > size) {
158+
throw new IndexOutOfBoundsException();
159+
}
157160
return new CustomListIterator<>(this, index);
158161
}
159162

@@ -220,6 +223,9 @@ public boolean addAll(Collection<? extends T> c) {
220223

221224
@Override
222225
public boolean addAll(int index, Collection<? extends T> c) {
226+
if (index < 0 || index > size) {
227+
throw new IndexOutOfBoundsException();
228+
}
223229
if (c.isEmpty()) {
224230
return false;
225231
}

src/test/java/by/andd3dfx/collections/custom/CustomArrayListTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,17 @@ public void listIteratorComplex() {
536536
assertThat(collectedItems).isEqualTo(List.of("Andrei", "Tikhon", "Tikhon", "Andrei", "Andrei", "Tikhon", "Nina"));
537537
}
538538

539+
@Test
540+
public void listIteratorWithIndex_InvalidIndex() {
541+
var list = new CustomArrayList<String>();
542+
list.add("Andrei");
543+
list.add("Tikhon");
544+
list.add("Nina");
545+
546+
assertThrows(IndexOutOfBoundsException.class, () -> list.listIterator(-1));
547+
assertThrows(IndexOutOfBoundsException.class, () -> list.listIterator(4));
548+
}
549+
539550
@Test
540551
public void listIteratorWithIndex() {
541552
var list = new CustomArrayList<String>();
@@ -568,6 +579,17 @@ public void subList() {
568579
assertThrows(NotImplementedException.class, () -> list.subList(1, 3));
569580
}
570581

582+
@Test
583+
public void testAddAllWithIndex_InvalidIndex() {
584+
var list = new CustomArrayList<>();
585+
list.add("Andrei");
586+
list.add("Tikhon");
587+
list.add("Ilya");
588+
589+
assertThrows(IndexOutOfBoundsException.class, () -> list.addAll(-1, List.of("Taisia", "Nika")));
590+
assertThrows(IndexOutOfBoundsException.class, () -> list.addAll(4, List.of("Taisia", "Nika")));
591+
}
592+
571593
@Test
572594
public void testAddAllWithIndex_NoResize() {
573595
var list = new CustomArrayList<>();

0 commit comments

Comments
 (0)