4

I would like to know how to return two multidimentional arrays from the same method:

public static arraysReturn() {
    int [][] A={{1,2},{2,3},{4,5}};
    int [][] B={{1,2},{2,3},{4,5}};
    return A,B;
}
1
  • A 3D array, with the first dimension as size 2? Commented Sep 16, 2014 at 16:07

3 Answers 3

6

Java does not support returning multiple things at once.

However, you could create a small class that does this:

public class TwoArrays {
    public final int[][] A;
    public final int[][] B;
    public TwoArrays(int[][] A, int[][] B) {
        this.A = A;
        this.B = B;
    }
}

Then make your method like this:

public static TwoArrays arraysreturn() {
    int [][] A={{1,2},{2,3},{4,5}};
    int [][] B={{1,2},{2,3},{4,5}};
    return new TwoArrays(A,B);
}

To access values:

TwoArrays arrays = arraysreturn();
System.out.println(Arrays.toString(arrays.A)); //Due to the way java prints arrays, this is needed, but it isn't a requirement for doing other stuff with the array.
System.out.println(Arrays.toString(arrays.B)); 
Sign up to request clarification or add additional context in comments.

4 Comments

if the fields are public I would recommend to set them "final"
It depends on what needs to be done. If you wanted to change the value, you could do that. But I'll label them as final to appease you.
This is a very good start, I use classes like this with public final variables to group returns quite a bit. The thing is, if you even remotly follow the SRP then those two pieces of data are related and SHOULD be parts of a class. After this keep an eye out for methods that operate only on this data, they should be methods OF your "TwoArrays" class. After a while you make the variables private, rename the class and you have done a fantastic proper OO refactor. This is one of the first steps in really understanding and working towards OO design.
I am curious to know how to capture the return values in main method? @Pokechu22
5

Make one array which contains both arrays. In your case

int[2][][] = {
    {{1,2},{2,3},{4,5}}, 
    {{1,2},{2,3},{4,5}}
};

Or better, make an object which contains both arrays.

1 Comment

downvote only in that it is a much better idea to add a class, complicating a structure which you have no insight into (from the calling class) is not a good solution. This works but nobody should ever do it.
2

You can't return multiple values from a method.

You can return a single Object that contains two arrays as members though.

You could also return a multi-dimensional array that contains both arrays, but that's not a very OOP solution.

Comments

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.