From e383b94e1b44a6f778f17a3fa805b454498609c2 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Mon, 25 Sep 2023 15:23:18 +0200 Subject: [PATCH] classlib: fix implementations of SequencedCollection methods in ArrayList --- .../teavm/classlib/java/util/TArrayList.java | 15 +++++++-- .../classlib/java/util/ArrayListTest.java | 32 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/util/TArrayList.java b/classlib/src/main/java/org/teavm/classlib/java/util/TArrayList.java index d7c47cae0..0cfed0e56 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/util/TArrayList.java +++ b/classlib/src/main/java/org/teavm/classlib/java/util/TArrayList.java @@ -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 extends TAbstractList 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 extends TAbstractList 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); diff --git a/tests/src/test/java/org/teavm/classlib/java/util/ArrayListTest.java b/tests/src/test/java/org/teavm/classlib/java/util/ArrayListTest.java index 5373ad02e..25f1eb4dd 100644 --- a/tests/src/test/java/org/teavm/classlib/java/util/ArrayListTest.java +++ b/tests/src/test/java/org/teavm/classlib/java/util/ArrayListTest.java @@ -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 + } + } }