Create DynamicArray.java
parent
a3f5a177a5
commit
6ca0b464a8
|
|
@ -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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue