0

Ok, so this is a shot in the dark but... Is there any way to overload the argument for multidimensional array access to take in custom arguments?

//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];

I am currently working in Java but I would also like to know if it is at all possible.

2
  • Why is it important to preserve the array-indexing syntax? This can be easily accomplished if you drop the requirement to use the syntax. Commented Jan 22, 2013 at 4:21
  • @JimGarrison it isn't, and again, thank you for your answer, and the extra note about it being [][] not [,], saved me from running into that problem just now :). When I can up-vote answers you are definitely getting one, you have been most helpful. Commented Jan 22, 2013 at 4:59

1 Answer 1

2

No. Java does not support operator overloading in the way C++ does.

Here's a Java version, in case you're interested:

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));
    }
}

Method get(...) takes an array of any reference type and an index object and returns the selected object. For primitives you'd need one specialized get method per primitive type.

Note also that array syntax in java is not [a,b] but [a][b].

Sign up to request clarification or add additional context in comments.

4 Comments

So would this be possible in the C languages?
You could do this in C++, not in C.
Cool, sad I can't do it in Java, but I knew it wasn't very likely to begin with. Thank you for your quick response Jim.
I am impressed. Jim that is just amazingly done. And I learned about generic methods from it. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.