Skip to content

Commit

Permalink
attempt 1
Browse files Browse the repository at this point in the history
  • Loading branch information
dantesworld committed Dec 26, 2024
1 parent 798d9ef commit a837ba9
Showing 1 changed file with 79 additions and 8 deletions.
87 changes: 79 additions & 8 deletions src/main/java/core/basesyntax/ArrayList.java
Original file line number Diff line number Diff line change
@@ -1,48 +1,119 @@
package core.basesyntax;

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

public class ArrayList<T> implements List<T> {

private static final int defaultSize = 10;
private Object[] arrayList = new Object[defaultSize];
private int size = 0;

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

@Override
public void add(T value) {

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

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

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

@Override
public void addAll(List<T> list) {

if (arrayList.length < size() + list.size()) {
grow();
}
for (int i = 0; i < list.size(); i++) {
add(list.get(i));
}
}

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

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

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

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

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

@Override
public T remove(T element) {
return null;
boolean removed = false;
Object[] newArrayList = new Object[arrayList.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;
}
newArrayList[newIndex++] = arrayList[i];
}
arrayList = newArrayList;

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 a837ba9

Please sign in to comment.