Element removal in generic array
-
import java.util.Arrays; public class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(45); numbers.add(78); numbers.add(10); numbers.add(17); numbers.add(89); numbers.add(16); System.out.println(numbers); numbers.removeAt(3); System.out.println(numbers); } } import java.util.Arrays; public class ArrayList<T> { private static final int DEFAULT_SIZE = 6; private T[] elements; private int size; public ArrayList() { this.elements = (T[])new Object[DEFAULT_SIZE]; this.size = 0; } /** * Добавляет элемент в конец списка * @param element добавляемый элемент */ public void add(T element) { // если массив уже заполнен if (isFullArray()) { resize(); } this.elements[size] = element; size++; } private void resize() { // запоминаем старый массив T[] oldElements = this.elements; // создаем новый массив, который в полтора раза больше предыдущего this.elements = (T[])new Object[oldElements.length + oldElements.length / 2]; // копируем все элементы из старого массива в новый for (int i = 0; i < size; i++) { this.elements[i] = oldElements[i]; } } private boolean isFullArray() { return size == elements.length; } /** * Получить элемент по индексу * @param index индекс искомого элемента * @return элемент под заданным индексом */ public T get(int index) { if (isCorrectIndex(index)) { return elements[index]; } else { return null; } } private boolean isCorrectIndex(int index) { return index >= 0 && index < size; } public void clear() { this.size = 0; } public void removeAt(int index) { elements.remove(elements[index]); } public String toString() { return Arrays.toString(elements); } }
-
Java Never Method
remove
andadd
Because they have Always. A fixed size applied to the creation of the mass. This size and return to the field.length
♪If necessary, reduce the size of the mass when removal of the element/small elements must first decrime
size
then move the remaining elements to the left (to the beginning of the mass) and, when a certain threshold is reached (e.g.,size < length / 2
to create a smaller mass, replicating the remaining elements.