我对我的代码有疑问。当我尝试从其删除索引后尝试获取arraylist.size()时,我不断获取IndexOutOfBoundsException。当原始大小为8,然后在我删除索引后,它应该下降到7,但随后保持为8。
谢谢你的帮助。
public class test {
public static void main(String[]args){
final Integer [] pickMove = {0,1,2,3,4,5,6,7};
ArrayList<Integer> possibleMove=new ArrayList<Integer>();
SecureRandom random = new SecureRandom();
boolean response = false;
int counter=0;
possibleMove.addAll(Arrays.asList(pickMove));
for(int i=0; i<pickMove.length && !response ; i++){
System.out.println("arrayList size:" +possibleMove.size());
int move=possibleMove.get(random.nextInt(possibleMove.size()));
System.out.println("move picked: "+move);
if(move==5){
response=true;
++counter;
}
else{
possibleMove.remove(move);
++counter;
}
for ( int j = 0; i < possibleMove.size(); j++ )
System.out.printf( " %s", possibleMove.get( j ) );
}
System.out.println("# of Tries to get to 5: "+counter);
}
}
最佳答案
它应该是j
for (int j = 0; j < possibleMove.size(); j++)
System.out.printf(" %s", possibleMove.get(j));
关于java - Arraylist移除方法,但超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33381531/