多个位置的IndexOutOfBoundsException

时间:2017-05-30 21:31:49

标签: java for-loop arraylist

只是做了一些编码并在我的代码中遇到了这个错误,并不完全确定原因。

import java.util.*;

public class JavaApplication5 {

public static void main(String[] args) {

    int val;
    int[] arrayE = {-2, 2, 3, 0};
    int[] arrayC = new int[4];

    arrayC[0] = 10;
    arrayC[1] = 20;
    arrayC[2] = 30;
    arrayC[3] = 40;

    for (val = 0; val < 4; val++){
        System.out.printf(arrayE[val] + " ");
        System.out.println(arrayC[val] + " ");
    }

 Map<String, Integer> ageMap = new HashMap<String, Integer>();
 ageMap.put("Jill", 3);
 ageMap.put("Kevin", 5);
 ageMap.put("James", 5);
 ageMap.put("Louise", 5);
 ageMap.put("Peter", 2);
 ageMap.put("Sally", 1);
 ageMap.remove("Kevin");
 ageMap.put("Jill", 1);

 System.out.println(ageMap.get(1));
 System.out.println(ageMap.values());
 System.out.println(ageMap.containsKey("Kevin"));
 System.out.println(ageMap.keySet());
 System.out.println(ageMap.get("Jill"));

 ArrayList listOne = new ArrayList();
 listOne.add("hello3");
 listOne.add("hello4");
 listOne.add("hello2");
 listOne.add("hello6");
 listOne.add("hello5");
 listOne.add("hello1");

 for (int i = 0; i <= listOne.size(); i++){
     System.out.println(listOne.get(i));
 }




 }

public int max(int[] vals){
int result = vals[0];
for(int i: vals){
    if(i > result)
 {
        result = i;
 }
}     
return result;
}


}

输出错误消息是因为我的ArrayList:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6

at java.util.ArrayList.rangeCheck(ArrayList.java:653)

at java.util.ArrayList.get(ArrayList.java:429)

at javaapplication5.JavaApplication5.main(JavaApplication5.java:48) 

知道为什么我的for循环会产生这样的错误?任何帮助赞赏。

1 个答案:

答案 0 :(得分:0)

列表索引从零开始。换句话说,如果列表中包含N个项目,则第一个列表将具有索引0,而最后一个列表将具有索引N-1。迭代listOne时,您的终止条件应使用<,而不是<=

for (int i = 0; i < listOne.size(); i++) {
    // Here ------^