Returning Multiple Objects from a Java Method: Elegant Solutions
Java, like many programming languages, inherently returns only a single object from a method. However, there are elegant ways to work around this limitation when you need to return multiple objects.
Consider the specific scenario where you need to return a list of objects and the comma-separated names of those objects. One common approach is to use a HashMap, mapping the names as keys to the objects as values. However, as you correctly noted, this can be unsightly.
A more efficient and maintainable solution is to create a custom encapsulating class that combines the two required objects. For instance, you could define a NamedObject class containing the object itself and its name.
public class NamedObject<T> { public final String name; public final T object; public NamedObject(String name, T object) { this.name = name; this.object = object; } }
With this class, you can return a List
Another option to consider is returning a Map
Finally, keep in mind that returning a comma-separated list of names is often inefficient. It would be preferable to return a List
The above is the detailed content of How Can I Elegantly Return Multiple Objects from a Java Method?. For more information, please follow other related articles on the PHP Chinese website!