java—向向量列表中添加元素

w9apscun  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(403)

这个问题在这里已经有了答案

什么是indexoutofboundsexception?我该怎么修[重复](1个答案)
上个月关门了。
我要浏览一个文件列表,把所有的单词都放在向量里。我列了一个向量列表,这样所有的“文件”都在同一个地方。但是,当我尝试在列表的第一个向量中添加一个单词时,它会给我一个错误“exception in thread”main“java.lang.indexoutofboundseception:index 1 out of bounds for length 0”我环顾四周看了看如何修复它,但是大多数相关的问题都是关于简单的arraylist,而不是关于arraylist的。这是我的密码:

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

我真的很感激任何帮助。

p4tfgftt

p4tfgftt1#

你得到这个错误是因为 documents 没有 Vector 加上它还没有因此尝试做什么 documents.get(i) 将导致 IndexOutOfBoundsException .
您可以添加 new Vector<String>() 进入 documents 具体如下:

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

将其添加到代码中的循环块之前。

niwlg2el

niwlg2el2#

我想你的密码必须这样改变。因为文档需要类型为 Vector<String> 不是类型 String .

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

相关问题