-1
該代碼應該將列表分區成集。如果ArrayList在一行中包含兩次相同的字符串,它將把它們的索引添加到一個HashSet,否則索引將位於不同的HashSets中。重點是將ArrayList中所有相同字符串的索引放入同一個HashSet中,並將不同字符串的索引放入不同的HashSets中。例如,程序應該打印[[0,1] [2,3]],但它被卡在無限循環中。我把一個打印語句來驗證前兩個索引是否被添加到HashSet中,他們是。該程序打印[[0,1]]而不是預期的結果。出於某種原因,即使我更新循環中的索引並且在第二次迭代中結果應該爲false,list.get(index1).equals(list.get(index2))總是計算爲true。無限循環Java爲深不可測的原因
package quiz;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Iterator;
public class Question {
public static void main(String[] args) {
Question q = new Question();
ArrayList<String> list2 = new ArrayList<String>();
list2.add("a");
list2.add("a");
list2.add("c");
list2.add("c");
System.out.println(q.answer(list2));
}
public HashSet<HashSet<Integer>> answer(ArrayList<String> list){
HashSet<HashSet<Integer>> hashSet = new HashSet<HashSet<Integer>>();
HashSet<Integer> set = new HashSet<Integer>();
Iterator<String> it = list.iterator();
int index1 = 0;
int index2 = 1;
while (it.hasNext()){
while (list.get(index1).equals(list.get(index2))){
set.add(index1);
set.add(index2);
if (index1<list.size()-2){
index1=index1+1;
index2=index2+1;
}
}
hashSet.add(set);
System.out.println(hashSet);
}
/*else{
set.add(i);
}*/
return hashSet;
}
}
提示:你在哪裏調用'it.next()'? –
爲了擴展Boris Spider的說法,只是從列表中獲取元素將不會推進所述列表的迭代器。 – rmlan
我現在很愛你們:D –