Return multiple values: Difference between revisions

Content added Content deleted
Line 1,597: Line 1,597:


=={{header|Java}}==
=={{header|Java}}==
Java does not have tuples, so the most idiomatic approach would be to create a nested or inner-class specific to your values.
<syntaxhighlight lang="java">
Point getPoint() {
return new Point(1, 2);
}

static class Point {
int x, y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
</syntaxhighlight>
It is not recommended to return an ''Object'' array from a method.<br />
This will require the receiving procedure a casting operation, possibly preceded by an ''instanceof'' conditional check.<br /><br />
If you're using objects that are not known until runtime, use Java Generics.
<syntaxhighlight lang="java">
Values<String, OutputStream> getValues() {
return new Values<>("Rosetta Code", System.out);
}

static class Values<X, Y> {
X x;
Y y;

public Values(X x, Y y) {
this.x = x;
this.y = y;
}
}
</syntaxhighlight>
<br />
Or, an alternate demonstration
{{trans|NetRexx}}
{{trans|NetRexx}}
<syntaxhighlight lang="java">import java.util.List;
<syntaxhighlight lang="java">import java.util.List;