2016-10-22 61 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()); 
} 
相关问题