简体   繁体   English

java:检查array [i] [j]是否在范围内

[英]java: check if array[i][j] within bounds

i have a 2-dimensional array of ints which i'm looping over. 我有一个整数数组,我正在遍历。 i want to check if an array's element i'm pointing at is within the bounds of that array. 我想检查我指向的数组元素是否在该数组的范围内。 say, if i had an array of size 3x2, i would like to be able to do this: 例如,如果我有一个3x2大小的数组,我希望能够做到这一点:

for(int i=some_variable;i<arrayWidth;i++) {
    for (int j=other_variable;j<arrayHeight;j++) {
        if (!array[i][j].ISOUTOFBOUNDS) {
            // do something
        }
    }
}

is there an eloquent way of achieving that or should i just check the indices manually? 有一种雄辩的方法可以实现这一目标,还是我应该手动检查索引?

ps. PS。 i and j can turn out to be negative, too, so i would like to check that as well. ij也可以是负数,所以我也想检查一下。

You can avoid performing this comparison n² time by pre-computing the valid ranges: 您可以通过预先计算有效范围来避免在n²时间执行此比较:

int maxValidI = Math.min(array.length, arrayWidth);
int maxValidJ = Math.min(array[0].length, arrayHeight);
int minValidI = Math.max(0, some_variable);
int minValidJ = Math.max(0, other_variable);

And then iterate i and j from minValidI and minValidJ to maxValidI and maxValidJ . 然后将i和j从minValidIminValidJmaxValidImaxValidJ

I hope it will help. 希望对您有所帮助。 Thanks to Andy for notifying me about OP's edit. 感谢Andy通知我关于OP的编辑。

Why not just get the length property of the arrays and use them as you limits in the control structure of if 为什么不只是获取数组的length属性并在if的控制结构中限制使用它们if

int arrayWidth = array.length;
for(int i = 0; i < arrayWidth; i++) {
    int arraySize = array[i].length;
    for (int j = 0; j < arraySize; j++) {

    }
}

// or if arrayHeight is from somewhere else

for(int i = 0; i < arrayWidth; i++) {
    int arraySize = array[i].length;
    for (int j = 0; j < arrayHeight; j++) {
        if (arrayHeight <= arraySize) {
            // do something
        }
    }
}

Also note array.length is the size of the array, but does not guarantee the index contains a non null value. 还要注意array.length是数组的大小,但不能保证索引包含非null值。 I would use ArrayList instead since it contains size() which is the size of the non null values. 我将使用ArrayList代替,因为它包含size() ,这是非null值的大小。

https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#size() https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#size()

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...) https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T ...)

You can't do it in the form you wrote it, but you can do something close: 您不能以编写的形式进行操作,但是可以做一些接近的事情:

if (isInBounds(array,i,j)) { ... }

Then you just need to implement isInbounds . 然后,您只需要实现isInbounds

You could make that method completely generic if you wanted to. 如果需要,可以使该方法完全通用。 Eg the following works for any array or array of arrays or ..., even nonuniform ones (eg an array of different sized arrays). 例如,以下内容适用于任何数组或数组数组,甚至是非均匀数组(例如,大小不同的数组的数组)。 Only catch is it won't work on arrays of primitive types cuz of the cast to Object[] . 唯一要注意的是,它不适用于强制转换为Object[]的基本类型cuz的数组。 Probably need more reflection stuff to handle that. 可能需要更多反射材料来处理该问题。

public static boolean isInBounds(Object arrayObj, int...indexes) {
  for (int i = 0; i < indexes.length; i++) {
    if (arrayObj == null || !arrayObj.getClass().isArray()) {
      return false; // we had too many indexes... ended up indexing a leaf element
    }
    Object[] array = (Object[]) arrayObj;
    if (indexes[i] < 0 || indexes[i] >= array.length) {
      return false;
    }
    arrayObj = array[indexes[i]];
  }
  return true;
}

i figured out a different way to do this. 我想出了另一种方式来做到这一点。

for(int i=some_variable;i<arrayWidth;i++) {
    for (int j=other_variable;j<arrayHeight;j++) {
        try {
            int tmp=array[i][j];
            // do something
        } catch (ArrayIndexOutOfBoundsException e) {
            continue;
        }
    }
}

what do you think of this approach? 您如何看待这种方法? it saves us from having to pre-compute the ranges and makes the code shorter and easier. 它使我们不必预先计算范围,并使代码更短,更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM