Create DynamicArray.java
This commit is contained in:
33
src/main/java/com/nbee/solution/practice/DynamicArray.java
Normal file
33
src/main/java/com/nbee/solution/practice/DynamicArray.java
Normal 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];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user