Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
Johnydep Avatar asked Jun 13 '11 22:06

Johnydep


People also ask

How can I return two arrays from a method in Java?

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.

Can you return two things from a method in Java?

Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.

Can you return an array in Java method?

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.


2 Answers

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

like image 76
anubhava Avatar answered Oct 04 '22 12:10

anubhava


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.

like image 44
Uchikoma Avatar answered Oct 04 '22 13:10

Uchikoma