2016-10-22 62 views
0

我有position,它等於顯示哪個問題。我想添加一個int等於position給arraylist。然後我想檢查一下,看看這個數組列表是否有int,防止再次添加int。使用下面的代碼,它會多次添加position int。只有當它不存在時,纔將int添加到arraylist

if(correctQuestions.size() == 0){ 
     correctQuestions.add(position); 
    }else if(correctQuestions.size() > 0){ 
     if(!Arrays.asList(correctQuestions).contains(position)){ 
      correctQuestions.add(position); 
     } 
    } 

如果position = 0;那麼這段代碼的每次運行將繼續增加position到我的ArrayList不管0是與否。例如,運行此代碼3次會導致我的數組列表輸出[0,0,0],只允許它添加0次。

回答

0

必須這樣寫:

if(correctQuestions.size() == 0){ 
    correctQuestions.add(position); 
}else if(correctQuestions.size() > 0){ 
    if(!correctQuestions.contains(position)){ 
     correctQuestions.add(position); 
    } 
} 
0

試試這個:

if(correctQuestions.indexOf(position) < 0) {//this will return -1 if object not found in the arraylist 
    correctQuestions.add(position); 
} 
0

你將擁有的ArrayList的最大指數假設它作爲變量大小。 所以你可以編寫條件邏輯:

if(size!=0 && position < size){ 
    correctQuestions.add(position); 
} 
0

的方法arrayList.size()返回列表中的項目數 - 所以,如果該指數大於或等於大小(),它不存在。

if(correctQuestions.size() > position){ 

     correctQuestions.add(position); 

} 

if you want to check if position already present in arraylist if `correctQuestions.get(index);` in try block shows that if no key present it will throw in catch 

try { 
    correctQuestions.get(index); 
} catch (IndexOutOfBoundsException e) { 
    correctQuestions.add(index, new Object()); 
} 
相關問題