I have homework to mimic the ArrayList data structure in Java. I am not allowed to use any 3rd party data structures or anything in java.Utils.package.
I got stuck on how to increase the array size dynamically.
I read the documentation at Class ArrayList and many online articles and I didn't figure out a solution.
I found a post here but the author does not recommend to use his solution. "FAKE resizable array"
This is part of my code:
//Implementation Class
package IncreaseArraySize;
public class StudentArrayList<E>{
private Object[] elements;
public StudentArrayList() {
elements = new Object[]{null, null};
}
public StudentArrayList(int capacity) {
elements = new Object[capacity];
for(int i = 0; i < capacity; i++){
elements[i] = null;
}
}
public void add(E e){
Boolean isItAdded = false;
for ( int i= 0; i < elements.length; i++) {
//assuming the 1st null is the end of the list
if(elements[i] == null){
elements[i] = e;
isItAdded = true;
break;
}
}
if(isItAdded == false){
int holdIndex = elements.length;
resizeArray(holdIndex+10);
elements[holdIndex] = e;
}
}
private void resizeArray(int newCapacity){
System.out.println("Resize the array 'elements' here");
}
public String toString(){
String stringOfElements="[";
Boolean notFirstElement = false;
for ( int i= 0; i < elements.length; i++) {
if(elements[i] != null){
if(notFirstElement) stringOfElements += ", ";
stringOfElements += elements[i];
notFirstElement = true;
}
}
stringOfElements += "]";
return stringOfElements;
}
}
//Main method
package IncreaseArraySize;
public class testMyArrayList {
public static void main(String[] args) {
StudentArrayList<String> myArrayList = new StudentArrayList<String>(2);
System.out.println("Initial list of elements = " + myArrayList.toString());
myArrayList.add("this works fine");
myArrayList.add("this works fine too");
System.out.println("List of elements = " + myArrayList.toString());
myArrayList.add("This doesn't work");
System.out.println("Array was resized: list of elements= " + myArrayList.toString());
}
}
Any help is appreciated.