gpt4 book ai didi

java - 对于 ArrayList 的每个循环都出现 NoSuchElementException

转载 作者:行者123 更新时间:2023-11-29 06:42:10 27 4
gpt4 key购买 nike

下面的类用于按行索引单词的位置。抛出错误的方法旨在将单独文档的索引附加到当前索引。也就是说,如果第一个文档中有 6 行,则附加文档的第一行应该被索引为第 7 行。

public class DocumentIndex {
// a NavigableMap implementation to store indexed words and their locations
private TreeMap<String, ArrayList<Integer>> map = new TreeMap<String, ArrayList<Integer>>();

/**
* A method to append another index onto the main index
* @param indexAppendix the additional index to be appended onto the main index
*/
public void append(DocumentIndex indexAppendix){
if(indexAppendix == null){
throw new NullPointerException();
}
Integer docEnd = 0; // the last line recorded in the main index
Set<String> set = map.keySet(); // a Set of the key values from map
//select each key
for(Iterator<String> iter = set.iterator(); iter.hasNext();){
String key = iter.next(); // the current key value
// for each key select contents and determine the highest value
for(Iterator<Integer> iter2 = this.find(key).iterator(); iter2.hasNext();){
Integer compare = iter2.next(); // the key index current value
if(compare>docEnd){
docEnd=compare;
}
}
}

// for each key find an index value
for(Iterator<String> iter = set.iterator(); iter.hasNext();){
String key = iter.next(); // the current key value
// for each index value map that value adjusting for the length of the original document
ArrayList<Integer> toAdd = new ArrayList<Integer>();
for(Iterator<Integer> iter2 = this.find(key).iterator(); iter2.hasNext();){
Integer addIter = iter2.next();
toAdd.add(addIter); // the current index value
}

/**
*Below is the loop in which the error is thrown
*/
for(Iterator<Integer> iter3 = toAdd.iterator(); iter.hasNext();){

Integer addIter = iter3.next(); // The error is thrown on this line

map.get(key).add(addIter+docEnd);
}
}
}

我做错了什么?

最佳答案

Louis Wasserman 做到了。

我只想指出,如果您使用“新的”Java for 循环语法,您的代码会简单很多,而且不会(不能!!)一开始就犯了那个错误。例如,使用"new"for 语法,您的代码大致如下所示:

    ...
Integer docEnd = 0;
Set<String> set = map.keySet();
for (String key : set) {
for (Integer compare : this.find(key)) {
if (compare < docEnd){
docEnd = compare;
}
}
}

for (String key : set) {
ArrayList<Integer> toAdd = new ArrayList<Integer>();
for (String add : this.find(key)) {
toAdd.add(add);
}
for (Integer add : toAdd) {
map.get(key).add(add * docEnd);
}
}

这不是更具可读性吗?


我将"new"用引号引起来,因为这种语法是在 2004 年发布的 Java 5 中引入的。到现在为止,它应该成为所有实践 Java 程序员……和讲师……的标准报告的一部分。

请不要复制粘贴以上代码。这只是为了说明我的观点。

关于java - 对于 ArrayList<Integer> 的每个循环都出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10255152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com