I have a method and I would like to return 3 types of data from it. I need a container class for that. I don't want to build it, but use a standard library class for it if this option exists.
I want to return from the method the following data at the same time:
LocalDate
LocalTime
- Message Object
My question - Is there a Class/Data Structure with Generics in the Java Standard libraries which I can use as container that I can assign the respective values to and that will allow me to return all these 3 values at the same time without me having to create it or use external libraries for?
If not, what other options to solve this issue do I have ?
CodePudding user response:
I once read a comment by one of the original designers who stated that they thought about providing classes like Pair, Triple or Tuple. However, they decided against it. Why? Because those classes are very generic and while it often makes sense to give proper names to the "things" in those classes. Example was Point(int x, int y)
instead of Pair(int a, int b)
. - So today "I don't want to build a container class" isn't a valid argument on most cases.
Java 17 's records make it easy to build those containers:
public static record Message(LocalDate date, LocalTime time, Object msg) {};
That's it.
Even without that creating those containers often is very simple by either having the IDE generate the methods or using some library like Lombok.
CodePudding user response:
The simplest way to return multiple values with different data types is by using arrays. In your method, append your desired values into an array and then return the array itself.
You can use a common parent type as the array's type if you want to return an array of different reference types.
LocalData[] getLocalDataArray() {
LocalData[] localDataArray = new LocalData[3];
localDataArray[0] = java.time.LocalDate.now(); // Date
localDataArray[1] = java.time.Time.now(); // Time
localDataArray[2] = "A message"; // String
return localDataArray;
}
You can find more info on How to Return Multiple Values From a Java Method