Update DynamicArray.java

master
wangsiyuan 2024-07-11 15:35:17 +08:00
parent 9eba905fc0
commit 9a98ed3770
1 changed files with 62 additions and 4 deletions

View File

@ -1,16 +1,22 @@
package com.nbee.solution.practice;
public class DynamicArray {
import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;
public class DynamicArray implements Iterable<Integer> {
private int size = 0;
private int capacity = 8;
private int[] array = new int[capacity];
private int[] array = {};
public void addList(int element) {
add(size, element);
}
public void add(int index, int element) {
if (index < 0 || index > size){
checkAndGrow();
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
if (index >= 0 && index < size) {
@ -20,14 +26,66 @@ public class DynamicArray {
size++;
}
private void checkAndGrow() {
if (size == 0) {
array = new int[capacity];
} else if (size == capacity) {
capacity = capacity + (capacity >>> 1);
int[] newArray = new int[capacity];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
}
public int getSize() {
return size;
}
public int get(int index) {
if (index < 0 || index >= size){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return array[index];
}
public void forEach0(Consumer<Integer> consumer) {
for (int i = 0; i < size; i++) {
consumer.accept(array[i]);
}
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int i = 0;
@Override
public boolean hasNext() {
return i < size;
}
@Override
public Integer next() {
return array[i++];
}
};
}
public IntStream stream() {
return IntStream.of(Arrays.copyOfRange(array, 0, size));
}
public int remove(int index) {
int removed = array[index];
if (index < size - 1) {
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
}
return removed;
}
public String toString() {
return Arrays.toString(Arrays.copyOfRange(array, 0, size));
}
}