Hello! So, I created my own Arraylist class called myArrayList.
I need to read a file that contains strings (which are just short phrases) into myArrayList.
I created a class called Phrase that are to be the objects that will be stored into the Arraylist. I also have a class called fileReader that simply reads the file.
I'm getting an Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at the grow() method in myArraylist
at add() method in myArraylist
at main() method
Here's my code:
public class myArrayList {
private Object array[];
private int totalSize; // the capacity of the array
private int currentItems; // the number of items currently stored in the array
public myArrayList(int n) {
array = new Object[n];
totalSize = n;
currentItems = 0;
}
public void add(Object i) { // Add item to the end of the array list
try {
array[currentItems] = i;
currentItems++;
}
catch (ArrayIndexOutOfBoundsException a) {
grow(); /****ERROR here*/
array[currentItems++] = i;
}
}
private void grow() { // Doubles totalSize in array list
Object[] newArray = new Object[2 * totalSize]; /****ERROR here*/
for (int i = 0; i < currentItems; i++) {
newArray[i] = array[i];
}
array = newArray;
totalSize = 2 * totalSize;
}
}
public class Phrase{
private String phrase;
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
}
public static void main(String[] args) {
myArrayList newArrayList = new myArrayList(20);
fileReader myFileReader = new fileReader(
"file.xml");
Phrase myPhrase = myFileReader.readFile();
Phrase newPhrase = new Phrase(myPhrase.getPhrase());
while (myPhrase != null) {
myArrayList.add(newPhrase); /****ERROR here*/
}
}
I don't know if what I'm trying to do is even headed in the right direction. Also, I do not know how to test to see what is in myArrayList once I stop getting errors.
Later, I need to sort and remove duplicates in myArrayList.
Thanks in advance!