1

How to create a JAVA function with multiple outputs? Something like:

private (ArrayList<Integer[]>, int indexes) sortObjects(ArrayList<Integer[]> arr) {
//...
}
2
  • 1
    What do you mean by multiple outputs? Are you referring to the return values? If this is the case, you should create a new class instead, and put your arraylist, int indexes and whatever else you want in there. Then modify the function to return your newly created class. Commented Jan 3, 2012 at 10:11
  • How about using a HashMap ? Commented Mar 22, 2013 at 12:26

7 Answers 7

5

Java's not like Python - no tuples. You have to create an Object and wrap all your outputs into it. Another solution might be a Collection of some sort, but I think the former means better encapsulation.

Sign up to request clarification or add additional context in comments.

1 Comment

2

In some cases it is possible to use method arguments to handle result values. In your case, part of the result is a list (which may be updated destructively). So you could change your method-signature to the following form:

private int sortObjects(ArrayList<Integer[]> input, ArrayList<Integer[]> result) {
   int res = 0;
   for (Integer[] ints : input) {
     if (condition(ints) {
       result.add(calculatedValue);
       res++
     }
   }
   return res;
}

Comments

1

You cannot, you can either

  • Create a wrapper return object
  • Create multiple functions

Comments

1

Use an object as return value.

class SortedObjects { private ArrayList<Integer[]> _first; int _indexes; ...getter/setter/ctor... }

private SortedObjects sortObjects(ArrayList<Integer[]> arr) { ... }

Comments

1

You cannot.

The simple solution is to return an array of objects. A more robust solution is to create a class for holding the response, and use getters to get the individual values from the response object returned by your code.

Comments

1

You have to create a class which includes member variables for each piece of information you require, and return an object of that class.

Comments

1

Another approach is to use an Object which wraps the collection.

class SortableCollection {
    final List<Integer[]> tables = ...
    int indexes = -1;

    public void sortObjects() {
        // perform sort on tables.
        indexes = ...
    }
}

As it operates on a mutable object, there is no arguments or return values.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.