Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
obaibula opened this issue Feb 22, 2023 · 0 comments
Open

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

obaibula opened this issue Feb 22, 2023 · 0 comments

Comments

@obaibula
Copy link

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);
    }
@shryhus shryhus added this to To do in Java Fundamentals Feb 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Development

No branches or pull requests

1 participant