无限循环Java是出于不可思议的原因



代码应该将列表划分为集合。如果阵列列表连续两次包含相同的字符串,则将其索引添加到一个哈希集,否则索引将在不同的标签中。关键是将来自阵列列表的所有相同字符串的索引放在相同的标签和不同标签中的不同字符串的索引中。例如,程序应打印[[0,1] [2,3]],但它被卡在无限的循环中。我提出了一个打印声明,以验证前两个索引是否正在添加到标签中。程序打印[[0,1]],而不是预期的结果。由于某些原因,list.get(index1).equals(list.get(index2))始终将其评估为true,即使我更新循环中的索引,结果在第二个迭代中应为false。

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;
}
}

您会得到一个无限的循环,因为您使用的是迭代器hasnext(),而不使用it.next()之后使用it.next()向前移动索引。

此外,您真的不需要迭代器,因为您不使用这些值。您应该做这样的事情:

while(shouldStop)
......
if (index1<list.size()-2){
   index1=index1+1;
   index2=index2+1;
} else {
   shouldStop=true
}
........

最新更新