1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class MultiArray {
/** classe interne représentant les coordonées d'un élément */
private static class Coor {
int x;
int y;
public Coor(int x, int y) {
this.x = x;
this.y = y;
}
}
/** Le tableau de tableaux */
final int[][] arrays;
/**
* Constructeur par défaut.
*/
public MultiArray(int[] ... arrays) {
this.arrays = arrays;
}
/**
* Traduction d'un index globale en coordonnée (x,y)
*/
private Coor translate(int index) {
int y = index;
for (int x=0; x<this.arrays.length; x++) {
if (y < this.arrays[x].length) {
// Si l'index est plus petit que le tableau
// => On a trouver notre index :
return new Coor(x, y);
} else {
// Sinon on doit passer au tableau suivant,
// en diminuant l'index de la taile du tableau
y -= this.arrays[x].length;
}
}
// Si on arrive ici c'est qu'on est allé trop loin :
throw new ArrayIndexOutOfBoundsException(index);
}
public int get(int index) {
Coor coor = translate(index);
return this.arrays[coor.x][coor.y];
}
public void set(int index, int value) {
Coor coor = translate(index);
this.arrays[coor.x][coor.y] = value;
}
public int size() {
int size = 0;
for (int[] array : this.arrays) {
size += array.length;
}
return size;
}
} |
Partager