Return two arrays in a method in Java Return two arrays in a method in Java arrays arrays

Return two arrays in a method in Java


You can actually return something like this also:

return new Object[]{array1, array2};

And let's say outside where you call this method your returned object is obj. Then get access to array1 as obj[0] and access array2 as obj[1] (proper casting will be needed).


Define an object that makes sense for what you're attempting to return. As an example:

public class Inventory {           private int[] itemNumbers; //array2      private String[] itemNames; //array1      public Inventory(int[] itemNumbers, String[] itemNames)      {         this.itemNumbers = itemNumbers;         this.itemNames = itemNames;      }      //Setters + getters. Etc.}

Then somewhere else:

return new Inventory(array2, array1); 

===============================================

Notes:

The above example is not a good example of an inventory. Create an item class that describes an item (item id, item name, etc) and store an array of those.

If your two arrays are unrelated, then the above is more of a cheap workaround. Ideally, you should split the computation and return of the arrays into their own method.

If the int/String arrays represent key/value pairs, then use can use a Map DST implementation (http://download.oracle.com/javase/6/docs/api/java/util/Map.html) instead and return that. You can iterate over key/values as necessary.


You can define Pair class as follows:

public class Pair{    private String[] array1;    private int[] array2;    public Pair(String[] array1, int[] array2)    {        this.array1 = array1;        this.array2 = array2;    }    public String[] getArray1() { return array1; }    public int[] getArray2() { return array2; }}

then you can use it in your method:

public Pair someMethod(){     String[] array1 = new String[10];     int[] array2 = new int[10];     // blah blah blah     return new Pair(array1, array2);}

and you can use your method as follows:

Pair pair = someMethod();String[] arrayA = pair.getArray1();int[] arrayB = pair.getArray2();