Skip to content

Commit

Permalink
Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
MaybeTI committed Dec 20, 2024
1 parent 798d9ef commit 77323a1
Showing 1 changed file with 80 additions and 8 deletions.
88 changes: 80 additions & 8 deletions src/main/java/core/basesyntax/ArrayList.java
Original file line number Diff line number Diff line change
@@ -1,48 +1,120 @@
package core.basesyntax;

import java.util.Arrays;
import java.util.NoSuchElementException;

public class ArrayList<T> implements List<T> {
private static final int ARRAY_START_SIZE = 10;
private Object[] list = new Object[ARRAY_START_SIZE];
private int size = 0;

private void grow() {
list = Arrays.copyOf(list, (int) (list.length * 1.5));
}

@Override
public void add(T value) {

if (list.length == size()) {
grow();
}
list[size()] = value;
size++;
}

@Override
public void add(T value, int index) {
if (index < 0 || index > size()) {
throw new ArrayListIndexOutOfBoundsException("Index out of range");
}
if (size() == list.length) {
grow();
}
Object[] newList = new Object[list.length];

for (int i = 0; i < index; i++) {
newList[i] = list[i];
}
newList[index] = value;
for (int i = index; i < size(); i++) {
newList[i + 1] = list[i];
}
list = newList;
size++;
}

@Override
public void addAll(List<T> list) {
public void addAll(List<T> otherList) {
if (list.length < size() + otherList.size()) {
grow();
}

for (int i = 0; i < otherList.size(); i++) {
add(otherList.get(i));
}

}

@Override
public T get(int index) {
return null;
if (index >= size() || index < 0) {
throw new ArrayListIndexOutOfBoundsException("Index out of range");
}
return (T) list[index];
}

@Override
public void set(T value, int index) {

if (index >= size() || index < 0) {
throw new ArrayListIndexOutOfBoundsException("Index out of range");
}
list[index] = value;
}

@Override
public T remove(int index) {
return null;
if (index >= size() || index < 0) {
throw new ArrayListIndexOutOfBoundsException("Index out of range");
}

final Object oldElement = list[index];
for (int i = index; i < size() - 1; i++) {
list[i] = list[i + 1];
}
list[size() - 1] = null;
size--;
return (T) oldElement;
}

@Override
public T remove(T element) {
return null;
boolean removed = false;
Object[] newList = new Object[list.length];
int newIndex = 0;

for (int i = 0; i < size(); i++) {
if (!removed && (get(i) != null ? get(i).equals(element) : get(i) == element)) {
removed = true;
size--;
continue;
}
newList[newIndex++] = list[i];
}
list = newList;

if (!removed) {
throw new NoSuchElementException("No such element " + element);
}

return element;
}

@Override
public int size() {
return 0;
return size;
}

@Override
public boolean isEmpty() {
return false;
return !(size() > 0);
}
}

0 comments on commit 77323a1

Please sign in to comment.