Question

I have the following situation:

final int I  = 10;
final int MU = 100;
final int P  = 100;

int[][] a = new int[I][MU];
int[][] b = new int[I][P];

for(int i = 0; i < I; i++) {
  for(int mu = 0; mu < MU; mu++) {
    for(int p = 0; p < P; p++) {
      a[i][mu] = ... // something
      b[i][p]  = ... // something
    }
  }
}

As you can see, I am using several arrays which have the same dimension, but which run over different indices. In this code, the following mistake may cause an ArrayIndexOutOfBoundsException, since mu has a larger range than i:

a[mu][i] = ...

In principle, I can catch this error. However, the following error is much harder to catch:

b[i][mu] = ...

Here there will be no runtime exception, since mu has the same range as p. This errors does cause semantic problems in the code, though.

Finally, my question: what is the best way to program these arrays in such a way that array a can only be accessed with the correct indices (i and mu in this case)?

Thanks!

Was it helpful?

Solution

It sounds like you should really encapsulate your data better. Any time you have two collections which are always the same size, consider changing to have one collection of some type which composes them.

We can't really tell what your type is meant to represent (hint: use more meaningful names) but if you had a class:

class Foo {
    private final int[] a = new int[MU];
    private final int[] b = new int[P];

    ...
}

Then you could have:

Foo[] foos = new Foo[I];

At that point it's very clear how the arrays are structured - you're very unlikely to do the wrong thing, because you'd have a loop such as:

for (int i = 0; i < foos.length; i++) {
    Foo foo = foo[i];
    // Use foo
}

I'd also encourage you to use the enhanced for loop:

for (Foo foo : foos) {
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top