Johnydep
Johnydep

Reputation: 6277

Return two arrays in a method in Java

Considering I have two arrays for example:

String[] array1 = new String[10];
int[] array2= new int[10];

So that inside a method I've computed two arrays, namely array1 & array2
and now I want to return both of these arrays. How should I go about it?

I read here that I can make another class and define certain object types and encapsulate these arrays in that class constructor, but I'm still confused and did not understand completely.

If you could show me a working example which does that, or may be any similar idea, it would be good.

Upvotes: 22

Views: 60141

Answers (10)

Hector Sanchez
Hector Sanchez

Reputation: 2317

You can create and return an Object array like this?

public Object[] ReturnObjectArray() {
    String[] array1 = new String[10];
    int[] array2 = new int[10];

    Object[] arrayObjects = new object[2];
    arrayObjects[0] = array1;
    arrayObjects[1] = array2;

    return arrayObjects;
}

You can then access them later like this:

Object[] arrayObjects = ReturnObjectArray();

String[] array1 = (String[]) arrayObjects[0];
int[] array2 = (int[]) arrayObjects[1];

Upvotes: 3

Razib
Razib

Reputation: 11173

A Map can be used. The advantage of using Map, one can return as many values as he wants. The implementation of this idea in code is something like -

public Map returnMultipleValues(){

 Map<String, Object> multiValues = new HashMap<String, Object>();
 String[] array1 = new String[10];
 int[] array2 = new int[10];

 //populate and manipulate these two array

 multiValues.put("array1", array1);
 multiValues.put("array2", array2);

 return multiValue;

}

Then in the calling function you can get these two values from the Map multiValues by using the keys - "array1", "array2":

String[] array1 = (String[]) multiValues.get("array1");
int[] array2 = (int[]) multiValues.get("array2");

Upvotes: 0

anubhava
anubhava

Reputation: 785691

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).

Upvotes: 52

phalgun kumar dandu
phalgun kumar dandu

Reputation: 29

Use new Object[]{array1, array2} to retun.

retun new Object[]{array1,array2};

And in caller method you will get returned object as "obj" then get

int[] array1 = obj[0] ;
int[] array2 = obj[1];

Upvotes: 0

Wesley
Wesley

Reputation: 10862

Based on your comment, there are a number of ways you can approach this.

  1. Create a class representing a user

    You mentioned that you're working with a 2D array of integers, where each row describes a single user. Perhaps it would be reasonable to have an object describing each user.

    class User {
        String name;
        int[] values;
    
        // setters and getters for name, values
    }
    
    User[] doSomething() {
         User[] users = new User[10];
    
         // fill the array
    
         return users;
    }
    
  2. Create a class representing the entire return value

    This is good if you really do need the extra performance of the 2D array.

    class UserData {
        String[] names;
        int[][] values;
    
        // setters and getters for names, values
    }
    
    UserData doSomething() {
        UserData userData = new UserData();
    
        // set names and values
    
        return userData;
    }
    

Upvotes: 0

Uchikoma
Uchikoma

Reputation: 71

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.

Upvotes: 7

Eng.Fouad
Eng.Fouad

Reputation: 117655

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

Upvotes: 6

mark-cs
mark-cs

Reputation: 4707

Apache commons lang has Pair in version 3 (which is in beta at the moment).

I would always advocate using trusted libraries over rolling your own (even if it is only a tuple).

One would have to ask why are you returning two values, how are they related. Generally in this situation the values are related and should be encapsulated in an object.

Upvotes: 1

duffymo
duffymo

Reputation: 308948

If these two are related, perhaps you'd be better off returning a java.util.Map, with one as key and the other as value, or a java.util.List containing objects of your own creation that encapsulates a String and int together.

Upvotes: 1

Babak Naffas
Babak Naffas

Reputation: 12571

Using public fields for simplicity of example. The same way a method can have a return type of an int, you can define your method to return a class type that you have defined.

class MyPair{
 public String[] StringArr;
 public int[] IntArr;
}

class MyClass{
   public MyPair Foo(){
    MyPair pair = new MyPair();
    pair.StringArr = new String[10];
    pair.IntArr = new int[10];

    return pair;
  }
}

Upvotes: 1

Related Questions