diff --git a/src/main/java/core/basesyntax/ArrayList.java b/src/main/java/core/basesyntax/ArrayList.java index 8d6477943..8c383cc07 100644 --- a/src/main/java/core/basesyntax/ArrayList.java +++ b/src/main/java/core/basesyntax/ArrayList.java @@ -1,48 +1,98 @@ package core.basesyntax; +import java.util.NoSuchElementException; +import java.util.Objects; + public class ArrayList implements List { + private int size = 0; + private Object[] array = new Object[10]; + @Override public void add(T value) { - + if (size == array.length) { + Object[] newArray = new Object[array.length + array.length / 2]; + System.arraycopy(array, 0, newArray, 0, array.length); + array = newArray; + } + array[size] = value; + size++; } @Override - public void add(T value, int index) { - + public void add(T value, int index) throws ArrayListIndexOutOfBoundsException { + if (index > size() || index < 0) { + throw new ArrayListIndexOutOfBoundsException("Index out of bounds"); + } + if (size == array.length) { + Object[] newArray = new Object[array.length + array.length / 2]; + System.arraycopy(array, 0, newArray, 0, array.length); + array = newArray; + } + System.arraycopy(array, index, array, index + 1, size() - index); + array[index] = value; + size++; } @Override public void addAll(List list) { - + int summarySize = list.size() + size(); + final int tempSize = summarySize; + if (summarySize > array.length) { + summarySize = summarySize + summarySize / 2; + Object[] newArray = new Object[summarySize]; + System.arraycopy(array, 0, newArray, 0, array.length); + array = newArray; + } + for (int i = 0; i < list.size(); i++) { + array[i + size] = list.get(i); + } + size = tempSize; } @Override - public T get(int index) { - return null; + public T get(int index) throws ArrayListIndexOutOfBoundsException { + if (index >= size() || index < 0) { + throw new ArrayListIndexOutOfBoundsException("Index out of bounds"); + } + return (T) array[index]; } @Override - public void set(T value, int index) { - + public void set(T value, int index) throws ArrayListIndexOutOfBoundsException { + if (index >= size() || index < 0) { + throw new ArrayListIndexOutOfBoundsException("Index out of bounds"); + } + array[index] = value; } @Override public T remove(int index) { - return null; + if (index >= size() || index < 0) { + throw new ArrayListIndexOutOfBoundsException("Index out of bounds"); + } + T result = (T) array[index]; + System.arraycopy(array, index + 1, array, index, array.length - index - 1); + size--; + return result; } @Override - public T remove(T element) { - return null; + public T remove(T element) throws NoSuchElementException { + for (int i = 0; i < size(); i++) { + if (Objects.equals(get(i), element)) { + return remove(i); + } + } + throw new NoSuchElementException(); } @Override public int size() { - return 0; + return size; } @Override public boolean isEmpty() { - return false; + return size() == 0; } }