Skip to content

2-2-5-array-list, removeElementByIndex fails with working code #160

Description

@obaibula

The following code is not accepted by 24-th test in ArrayListTest. But this code works just fine.

@Override
    @SuppressWarnings("unchecked")
    public T remove(int index) {
        Objects.checkIndex(index, size);

        T removedElement = (T) elements[index];
        Object[] copy = new Object[elements.length];

        System.arraycopy(elements, 0, copy, 0, index);
        System.arraycopy(elements, index + 1, copy, index, size - index - 1);

        elements = copy;
        size--;
        return removedElement;
    }

It works perfectly, if you just move internalArray initialization down like this:

@Test
    @Order(24)
    void removeElementByIndex() {
        fillTestArray(15, 69, 58, 78, 100);


        int removedElement = arrayList.remove(2);

        Object[] internalArray = getTestArray();

        assertThat(internalArray[2]).isEqualTo(78);
        assertThat(internalArray[1]).isEqualTo(69);
        assertThat(getTestSize()).isEqualTo(4);
        assertThat(removedElement).isEqualTo(58);
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions