0

さて、これは暗闇の中でのショットですが...多次元配列アクセスの引数をオーバーロードしてカスタム引数を取り込む方法はありますか?

//normal array access
myArray[1][2];

//I have a class with two ints and do this
myArray[int2Var.x][int2Var.y];

//is there any way to overload the array arguments so I can do this to access a two dimensional array?
myArray[int2Var];

私は現在Javaで作業していますが、それが可能かどうかも知りたいです。

4

1 に答える 1

2

いいえ。Javaは、C++のように演算子のオーバーロードをサポートしていません。

興味のある方のために、Javaバージョンを次に示します。

public class Test {

    public static class Index
    {
        int x;
        int y;
    }
    public static <T> T get(T[][] array, Index i)
    {
        return array[i.x][i.y];
    }
    public static void main(String[] args)
    {
        Index ix = new Index();
        ix.x = 1;
        ix.y = 2;

        Integer[][] arr = new Integer[3][3];
        for (int i=0; i<3; i++)
            for (int j=0; j<3; j++)
                arr[i][j] = 3*i + j;

        System.out.println(get(arr,ix));
    }
}

メソッドget(...)は、任意の参照型の配列とインデックスオブジェクトを受け取り、選択されたオブジェクトを返します。getプリミティブの場合、プリミティブ型ごとに1つの特殊なメソッドが必要になります。

また、Javaの配列構文はではないことにも注意して[a,b]ください[a][b]

于 2013-01-22T04:20:02.903 に答える