Hend
Hend

Reputation: 599

Android - Return multiple values from a method

I am retrieving 2 strings from the http connection. E.g. Name and Description, and will be storing them in 2 different arrays. The arrays would be used by another class of mine. I created 2 methods for searching each of them (searchName and searchDesc). Everything is working just fine but I would like to make it more efficient as I'm not doing so.

I would like to create a connection in one method, read and store the contents in their individual arrays and return the 2 arrays.

In other words, I want the app to only create connection/read through the html codes once only instead of twice(my current code). Instead of creating 2 methods to return only 1 value each, I want a method which returns 2 values. Is it possible and how?

Upvotes: 4

Views: 16563

Answers (2)

LuxuryMode
LuxuryMode

Reputation: 33741

I want a method which returns 2 values. Is it possible and how?

No this is strictly not possible in Java. However, since you're using Java, which is an OO language, just create your own custom data type and return that..for example:

public class ResponseObject {

 private ArrayList<String> names = new ArrayList<String>();
 private ArrayList<String> descriptions = new ArrayList<String>();

 public void addName(String name) {
   names.add(name)
 }

 public void addDescription(String desc) {
   descriptions.add(desc)
 }

 public ArrayList<String> getNames() {
   return names;
 }

 public ArrayList<String> getDescriptions() {
   return descriptions;
 }

}

Upvotes: 21

Lalit Poptani
Lalit Poptani

Reputation: 67286

So, can't you just add your two values in an ArrayList<String> and return the ArrayList object and get the two values from that? I think this can be done.

Else the better option can be using a Map<String, String> that you can use to put the values with the key and also can get using the key.

Upvotes: 2

Related Questions