1

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

private (ArrayList<Integer[]>, int indexes) sortObjects(ArrayList<Integer[]> arr) {
//...
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • 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. – Manish Jan 03 '12 at 10:11
  • How about using a HashMap ? – James P. Mar 22 '13 at 12:26

7 Answers7

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
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;
}
Jonathan
  • 2,698
  • 24
  • 37
1

You cannot, you can either

  • Create a wrapper return object
  • Create multiple functions
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
1

Use an object as return value.

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

private SortedObjects sortObjects(ArrayList<Integer[]> arr) { ... }
Matten
  • 17,365
  • 2
  • 42
  • 64
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.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
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.

James McLeod
  • 2,381
  • 1
  • 17
  • 19
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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130