【问题标题】:Adding an element to a list of vectors [duplicate]将元素添加到向量列表中[重复]
【发布时间】:2021-02-26 05:54:24
【问题描述】:

我必须浏览一个文件列表并将他们所有的单词放在向量中。我制作了一个向量列表,以便所有“文件”都在同一个地方。但是,当我尝试在列表的第一个向量中添加一个单词时,它给了我一个错误“线程“主”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++;  
}

我真的很想得到任何帮助。

【问题讨论】:

标签: java file arraylist vector


【解决方案1】:

您收到此错误是因为documents 尚未添加任何Vector,因此尝试执行documents.get(i) 将导致IndexOutOfBoundsException

您可以将new Vector&lt;String&gt;() 添加到documents 中,如下所示:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-02
      • 2017-04-16
      • 2015-10-02
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      相关资源
      最近更新 更多