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.
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.
Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With