Java 将元素添加到向量列表中

Java 将元素添加到向量列表中,java,file,arraylist,vector,Java,File,Arraylist,Vector,我必须浏览一个文件列表,并将它们的所有单词放入向量中。我制作了一个向量列表,这样所有的“文件”都在同一个地方。然而,当我尝试在列表的第一个向量中添加一个单词时,它会给我一个错误“线程中的异常”main“java.lang.IndexOutOfBoundsException:索引1超出长度0的界限”我环顾四周,看看如何修复它,但大多数相关问题都是关于简单的ArrayList,而不是ArrayList。这是我的密码: public static ArrayList<Vector<Stri

我必须浏览一个文件列表,并将它们的所有单词放入向量中。我制作了一个向量列表,这样所有的“文件”都在同一个地方。然而,当我尝试在列表的第一个向量中添加一个单词时,它会给我一个错误“线程中的异常”main“java.lang.IndexOutOfBoundsException:索引1超出长度0的界限”我环顾四周,看看如何修复它,但大多数相关问题都是关于简单的ArrayList,而不是ArrayList。这是我的密码:

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++;  
}
publicstaticarraylistdocuments=newarraylist(1000);
int i=0;
for(String file:trainingDataA)//trainindDataA是包含所有文件的数组
{
numDocA++;//它通过的文档数
文件d=新文件(文件);
String[]doc=d.extractWords(docWords);//解析文件并返回字符串数组
for(字符串w:doc)
documents.get(i).addElement(w);//这里是我得到错误的地方,我只想添加所有
//数组(文件字)的字符串到
//名单
//所以每个文件都有自己的向量和单词
i++;
}

我非常感谢您的帮助。

您收到此错误是因为
文档
尚未添加任何
向量
,因此尝试执行
文档。get(I)
将导致
索引自动边界异常

您可以将
new Vector()
添加到
文档中,如下所示:

documents.add(new Vector<String>()); // Add this line
documents.add(new Vector());//添加这一行

在代码中的循环块之前添加它。

我认为您的代码必须这样更改。因为文档需要类型为
Vector
的对象,而不是类型为
String

Vector<String> fileWords = new Vector<String>();
for (String w : doc)
    fileWords.add(w);
documents.add(i,fileWords);
Vector fileWords=new Vector();
for(字符串w:doc)
添加(w);
文件。添加(i,fileWords);

这是否回答了您的问题?