处理ArrayList越界异常Java

时间:2014-12-01 17:53:10

标签: java arrays exception arraylist exception-handling

我的程序将创建一个二维网格/ ArrayList。它将搜索特定框周围的所有框并返回其元素。但是,如果框位于边缘,则网格中可能没有任何周围的框。所以我们将尝试访问arrayList中的空槽,可能是slot -1。

无论如何,我可以在Java中编写这样的代码:

ArrayList arr = new ArrayList();

//add 5 elements to arr

for(int i = 0; i<10; i++){

    if(arr.get(i) is out of bounds){

        System.out.println("No elements here");

    else{

        System.out.println(arr.get(i));

    }

2 个答案:

答案 0 :(得分:1)

您可以检查我是否在数组范围之外。

  

如果i&gt; = arr.size();

虽然更好的解决方案是使用for循环遍历数组的内容,如下所示:

for (Object i : arr){
     // Do something
}

答案 1 :(得分:0)

您需要进行边界控制检查。例如,如果你需要绕点x,y的邻居循环,你可以做

// assuming that you're checking around point x and y

// here you set minI, maxI
int minI = Math.max(0, x - 1);
int maxI = Math.min(listMax - 1, x + 1);

for (int i = minI; i <= maxI; i++) { 

   // here you set minJ and maxJ
   int minJ = Math.max(0, y - 1);
   int maxJ = Math.min(innerListMax - 1, y + 1); 

   for (int j = minJ; j <= maxJ; j++) {
       // do your stuff here
   }
}