Skip to content

Instantly share code, notes, and snippets.

@TuHuynhVan
Created February 7, 2020 05:15
Show Gist options
  • Save TuHuynhVan/e65b619ca6b5a00e7212314883e5744b to your computer and use it in GitHub Desktop.
Save TuHuynhVan/e65b619ca6b5a00e7212314883e5744b to your computer and use it in GitHub Desktop.
package arraylist.practice;
public class MyArrayList {
static final int INITIAL_ARRAY_LENGHT = 10;
private Integer[] container;
private int nodeIndexToStoreData;
public static void main(String[] args) {
MyArrayList arrList = new MyArrayList();
// Make sure add/get/resize function work
arrList.add(1);
arrList.add(2);
arrList.add(3);
arrList.add(4);
arrList.add(5);
arrList.add(6);
arrList.add(7);
arrList.add(8);
arrList.add(9);
arrList.add(10);
arrList.add(11);
System.out.println("Array List Size: " + arrList.size());
System.out.println("Last Element: " + arrList.get(10));
// TODO: add more test case
}
public MyArrayList() {
this.container = new Integer[INITIAL_ARRAY_LENGHT];
this.nodeIndexToStoreData = 0;
}
public void add(int n) {
if (this.nodeIndexToStoreData == this.container.length - 1)
this.increaseArrayListSize();
this.container[this.nodeIndexToStoreData] = n;
this.nodeIndexToStoreData++;
}
public Integer get(int index) {
if (index > this.nodeIndexToStoreData - 1)
throw new Error("[ERR] Out of index");
return this.container[index];
}
public void set(int index, int n) {
if (index > this.nodeIndexToStoreData - 1)
throw new Error("[ERR] Out of index");
this.container[index] = n;
}
public Integer remove(int index) {
if (index > this.nodeIndexToStoreData - 1)
throw new Error("[ERR] Out of index");
int deletedValue = this.container[index];
this.container[index] = null;
return deletedValue;
}
public Integer size() {
return this.nodeIndexToStoreData + 1;
}
private void increaseArrayListSize() {
Integer[] copiedArray = this.container;
this.container = new Integer[copiedArray.length + INITIAL_ARRAY_LENGHT];
for (int i = 0; i < copiedArray.length; i++) {
this.container[i] = copiedArray[i];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment