English 中文(简体)
java applet - 阵列检查
原标题:java applet - array checking
最佳回答

一般来说,只有确保该指数属于受约束范围,才能防止<代码>ArrayIndexOutOfBoundsException。

JLS 10.4 Array Access

所有阵列都是零。 长度<代码>n的阵列,可按下列编码加以索引:0n-1

因此,这种简单检查非常典型:

if (i >= 0 && i < arr.length) {
    System.out.println(arr[i]);
}

诸如<代码>arr等新事物 以上编码在检查和取用之间重新分配,将NEVER<>>>/em> throw>。


2D array "boards"

通常,你会更具体,例如,如果你储存在两维阵列(或 Java的阵列)。

final int M = 10;  // height, i.e. number of rows
final int N = 8;   // width, i.e. number of columns
final int[][] board = new int[M][N];

那么,你可以采用以下方法:

boolean isInBound(int r, int c) {
    return (r >= 0) && (r < M) && (c >= 0) && (c < N);
}

由于我们知道我们有一个MxN的委员会,因此约束检查不仅容易阅读,也容易书写。 如果isInBound(r, c),则板[r][c]NEVER throwArrayIndexOutOfBoundsException

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...