Is it possible to return two or more values from a method to main in Java? If so, how it is possible and if not how can we do?
-
2Return array, list, set, map or your custom object containing multiple values. I have seen this same question somewhere.... let me find that. There are multiple questions on this topic: stackoverflow.com/search?q=return+multiple+values+in+java%3FHarry Joy– Harry Joy2011-12-19 06:10:41 +00:00Commented Dec 19, 2011 at 6:10
-
Maybe too late, but Just use java.util.AbstractMap.SimpleIEntry. Reusable, everywher since 1.6yerlilbilgin– yerlilbilgin2020-02-04 07:47:17 +00:00Commented Feb 4, 2020 at 7:47
-
If you are on Java 14+, it is better in general to use a Java Record instead of a SimpleEntry for representing a pair of values.Jason– Jason2021-01-30 14:52:47 +00:00Commented Jan 30, 2021 at 14:52
Add a comment
|
3 Answers
You can return an object of a Class in Java.
If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.
If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.
6 Comments
Kris
I would add one more point to this - keep your returned object immutable (best initialize it in a constructor and keep your fields final)
EKanadily
You can return an object , but if you have so many return objects in your program it makes the source code complicated. for things that are returned from a method once-of-its-kind-it-the-program better to have Tuples. like c#. darling c# its a great language
Mahesha999
I guess there should be C#
out or ref parameter equivalent in Java, otherwise I will need to create class even for returning two variables and for each function returning multiple values. If we follow this, then there will be a class for every function returning multiple values. Though using Map feels better approach now.Saqib Javed
I would use a map or set for keeping it simple :)
Lluis Martinez
Returning maps, lists or sets (to avoid returning a DTO) IMHO is an antipattern.
|
You can do something like this:
public class Example
{
public String name;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]= name;
ar[1] = location;
return ar; //returning two values at once
}
}
1 Comment
Aaron Franke
How performance efficient is this?