D
D
DMITRY T.2021-05-23 19:33:02
Java
DMITRY T., 2021-05-23 19:33:02

How does this remove method work?

package main;

public class MyArrayList {
    private String[] array = new String[10];
    private int size = 0;

    public void remove(int index) {
        if (index >= 0 && index < size) {
            for (int i = index; i < array.length - 1; i++) {
                array[i] = array[i + 1];
            }
            size--;
        }
    }
    public void add(String s) {
        array[size] = s;
        size++;
        if (size == array.length) {
            String[] newArray = new String[array.length * 2];
            for (int i = 0; i < array.length; i++) {
                newArray[i] = array[i];
            }
            array = newArray;
        }
    }


}


The principle of operation seems to be clear - the method assigns the value of the next element to the current element. But it turns out that if the penultimate element is assigned the value of the last one and the method stops working on this, then the last element and the penultimate one will have the same values?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-05-23
@Chuvaaak

Well, yes, it will, but the last element will no longer need to be looked at, due to the fact that size is there, this is the logical size of this container.
And there is extra work going on in the for loop. i < array.length - 1, which should be < size.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question