Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two multidimetional arrays from same java method?

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;
}
like image 610
user4047127 Avatar asked Dec 12 '22 03:12

user4047127


1 Answers

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)); 
like image 110
Pokechu22 Avatar answered Feb 01 '23 22:02

Pokechu22