classlib: fix implementations of SequencedCollection methods in ArrayList

This commit is contained in:
Alexey Andreev 2023-09-25 15:23:18 +02:00
parent 55426b25cf
commit e383b94e1b
2 changed files with 45 additions and 2 deletions

View File

@ -16,6 +16,7 @@
package org.teavm.classlib.java.util;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import org.teavm.classlib.java.io.TSerializable;
@ -66,12 +67,14 @@ public class TArrayList<E> extends TAbstractList<E> implements TCloneable, TSeri
@Override
public E getFirst() {
return get(0);
checkIfNotEmpty();
return array[0];
}
@Override
public E getLast() {
return get(size - 1);
checkIfNotEmpty();
return array[size - 1];
}
@Override
@ -124,14 +127,22 @@ public class TArrayList<E> extends TAbstractList<E> implements TCloneable, TSeri
@Override
public E removeFirst() {
checkIfNotEmpty();
return remove(0);
}
@Override
public E removeLast() {
checkIfNotEmpty();
return remove(size - 1);
}
private void checkIfNotEmpty() {
if (isEmpty()) {
throw new NoSuchElementException();
}
}
@Override
public E remove(int index) {
checkIndex(index);

View File

@ -29,6 +29,7 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;
@ -290,4 +291,35 @@ public class ArrayListTest {
lit.add("x");
assertEquals(List.of("d", "x", "a"), list);
}
@Test
public void sequenceCollectionMethodsOnEmpty() {
var empty = new ArrayList<>();
try {
empty.getFirst();
fail();
} catch (NoSuchElementException e) {
// ok
}
try {
empty.getLast();
fail();
} catch (NoSuchElementException e) {
// ok
}
try {
empty.removeFirst();
fail();
} catch (NoSuchElementException e) {
// ok
}
try {
empty.removeLast();
fail();
} catch (NoSuchElementException e) {
// ok
}
}
}