-1

I have to go through a list of file and place all their words inside vectors. I made a list of vectors so that all the "files" are in the same place. However, when I try to add a word inside the first vector of the list it gives me an error "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 0" I looked around to see how I could fix it but most of the questions related are about a simple ArrayList and not of ArrayList<Vector>. Here is my code:

public static ArrayList<Vector<String>> documents = new ArrayList<Vector<String>>(1000);
int i = 0;
for(String file : trainingDataA) //trainindDataA is an array with all the files
{
    numDocA++;  //number of documents it went through
    Document d = new Document(file);
    String [] doc = d.extractWords(docWords); //parses the file and returns an array of strings
            
    for (String w : doc)
        documents.get(i).addElement(w);  //here is where I get the error, I just want to add all the 
                                         //string of the array (file words) to the first vector of 
                                         //the list 
                                         //so that every file has its own vector with its own words

    i++;  
}

I would really appriciate any help.

Student
  • 55
  • 4
  • Does this answer your question? [ArrayIndexOutofBounds Exception from Adding Element to Vector of Vectors](https://stackoverflow.com/questions/50460371/arrayindexoutofbounds-exception-from-adding-element-to-vector-of-vectors) – lorenzozane Nov 14 '20 at 13:14

2 Answers2

1

You are getting this error because documents does not have any Vector added to it yet and therefore the attempt to do documents.get(i) will result in the IndexOutOfBoundsException.

You can add new Vector<String>() into documents as follows:

documents.add(new Vector<String>()); // Add this line

Add it before the loop block in your code.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

I think your code must change like this. Because documents need object of type Vector<String> not type String.

Vector<String> fileWords = new Vector<String>();
for (String w : doc)
    fileWords.add(w);
documents.add(i,fileWords);