Skip to content

Commit

Permalink
array3
Browse files Browse the repository at this point in the history
  • Loading branch information
VovaPryt committed Dec 17, 2024
1 parent fe9d806 commit a22cf5b
Showing 1 changed file with 8 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/main/java/core/basesyntax/ArrayList.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@

public class ArrayList<T> implements List<T> {
private static final int DEFAULT_CAPACITY = 10;
private static final double DEFAULT_MAGNIFICATION = 1.5;
private T[] elements;
private int size;

public ArrayList() {
elements = (T[]) new Object[DEFAULT_CAPACITY];
size = 0;
}

@Override
public void add(T value) {
growIfNeeded();
elements[size] = value;
size++;

}

@Override
Expand Down Expand Up @@ -63,8 +64,8 @@ public T remove(int index) {
@Override
public T remove(T element) {
for (int i = 0; i < size; i++) {
if ((elements[i] == null && element == null) || (elements[i]
!= null && elements[i].equals(element))) {
if (elements[i] == null && element == null || elements[i]
!= null && elements[i].equals(element)) {
return remove(i);
}
}
Expand All @@ -83,7 +84,7 @@ public boolean isEmpty() {

private void growIfNeeded() {
if (size == elements.length) {
int newCapacity = (int) (elements.length * 1.5);
int newCapacity = (int) (elements.length * DEFAULT_MAGNIFICATION);
T[] newElements = (T[]) new Object[newCapacity];
System.arraycopy(elements, 0, newElements, 0, elements.length);
elements = newElements;
Expand All @@ -94,7 +95,7 @@ private void ensureCapacity(int minCapacity) {
if (minCapacity > elements.length) {
int newCapacity = elements.length;
while (newCapacity < minCapacity) {
newCapacity = (int) (newCapacity * 1.5);
newCapacity = (int) (newCapacity * DEFAULT_MAGNIFICATION);
}
T[] newElements = (T[]) new Object[newCapacity];
System.arraycopy(elements, 0, newElements, 0, size);
Expand All @@ -103,16 +104,11 @@ private void ensureCapacity(int minCapacity) {
}

private void shiftRight(int index) {
for (int i = size; i > index; i--) {
elements[i] = elements[i - 1];
}
System.arraycopy(elements, index, elements, index + 1, size - index);
}

private void shiftLeft(int index) {
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
elements[size - 1] = null;
System.arraycopy(elements, index + 1, elements, index, size - index - 1);
}

private void checkIndex(int index) {
Expand Down

0 comments on commit a22cf5b

Please sign in to comment.