Create DynamicArray.java

master
wangsiyuan 2024-07-11 10:41:38 +08:00
parent a3f5a177a5
commit 6ca0b464a8
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package com.nbee.solution.practice;
public class DynamicArray {
private int size = 0;
private int capacity = 8;
private int[] array = new int[capacity];
public void addList(int element) {
add(size, element);
}
public void add(int index, int element) {
if (index < 0 || index > size){
throw new IndexOutOfBoundsException();
}
if (index >= 0 && index < size) {
System.arraycopy(array, index, array, index + 1, size - index);
}
array[index] = element;
size++;
}
public int getSize() {
return size;
}
public int get(int index) {
if (index < 0 || index >= size){
throw new IndexOutOfBoundsException();
}
return array[index];
}
}