2016-11-29 6 views
-1

コードはリストをセットに分割することになっています。 ArrayListに同じ文字列が2回連続して含まれる場合、そのインデックスは1つのHashSetに追加されます。そうでない場合、インデックスは異なるHashSetになります。ポイントは、同じHashSetのArrayListからのすべての同じ文字列のインデックスと、異なるHashSetの異なる文字列のインデックスを配置することです。例えば、プログラムは[[0、1] [2,3]]を印刷しなければならないが、無限ループに詰まっている。最初の2つのインデックスがHashSetに追加されているかどうかを確認するprintステートメントを置いています。プログラムは期待される結果の代わりに[[0、1]]を表示します。何らかの理由で、ループ内のインデックスを更新しても、結果は2回目の繰り返しで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; 
} 
} 
+5

ヒント:ここでは 'it.next()'を呼び出しますか? –

+1

Boris the Spiderが言っていることを拡張するために、単にリストから要素を取得するだけでは、そのリストの反復子は前進しません。 – rmlan

+0

私は今あなたが大好きです:D –

答えて

1

あなたは(イテレータのhasNextを(使用)が、it.nextを使用していないので、あなたは無限ループを取得します)。

さらに、値を使用していないため、イテレータは実際には必要ありません。

while(shouldStop) 
...... 
if (index1<list.size()-2){ 
    index1=index1+1; 
    index2=index2+1; 
} else { 
    shouldStop=true 
} 
........ 
関連する問題