Skip to content

Commit

Permalink
realised class ArrayList
Browse files Browse the repository at this point in the history
create const: DEFAULT_CAPACITY,
GROW_FACTOR
implements: add() - 3, get(), set(),
remove() - 2, size(), isEmpty()
added the methods grow(), checkIndex()
  • Loading branch information
aksoli666 committed Oct 30, 2023
1 parent 97ba460 commit fad322e
Showing 1 changed file with 81 additions and 6 deletions.
87 changes: 81 additions & 6 deletions src/main/java/core/basesyntax/ArrayList.java
Original file line number Diff line number Diff line change
@@ -1,48 +1,123 @@
package core.basesyntax;

import java.util.NoSuchElementException;

public class ArrayList<T> implements List<T> {
private static final int DEFAULT_CAPACITY = 10;
private static final double GROWTH_FACTOR = 1.5;
private Object[] values;
private int size;
private T oldValue;

public ArrayList() {
values = new Object[DEFAULT_CAPACITY];
}

@Override
public void add(T value) {

grow();
values[size] = value;
size++;
}

@Override
public void add(T value, int index) {
if (index < 0 || index > size) {
throw new ArrayListIndexOutOfBoundsException("Index out of bounds " + index);
}

grow();

if (index == size) {
values[size++] = value;
} else {
System.arraycopy(values, index, values, index + 1, size - index);
values[index] = value;
size++;
}
}

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

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

@Override
public T get(int index) {
return null;
checkIndex(index);

return (T) values[index];
}

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

oldValue = (T)values[index];
values[index] = value;
}

@Override
public T remove(int index) {
return null;
checkIndex(index);

oldValue = (T)values[index];

for (int i = index; i < size - 1; i++) {
values[i] = values[i + 1];
}

size--;
values[size] = null;
return oldValue;
}

@Override
public T remove(T element) {
return null;
int index = -1;

for (int i = 0; i < size; i++) {
if ((element == null && values[i] == null)
|| (element != null && element.equals(values[i]))) {
index = i;
break;
}
}

if (index == -1) {
throw new NoSuchElementException("Element not found " + element);
}

return remove(index);
}

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

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

private void grow() {
if (size == values.length) {
int newCapacity = (int)(values.length * GROWTH_FACTOR);
Object[] newValues = new Object[newCapacity];
System.arraycopy(values, 0, newValues, 0, size);
values = newValues;
}
}

private void checkIndex(int index) {
if (index < 0 || index >= size) {
throw new ArrayListIndexOutOfBoundsException("Index out of bounds " + index);
}
}
}

0 comments on commit fad322e

Please sign in to comment.