Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Returning a Record of Data  RSS feed

 
Ranch Hand
Posts: 569
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes it is necessary for a method to return a set of values instead of a single primitive type. What would be the best way to do this without creating another public class? For example, if I want to calculate the new coordinate of a point base on its old coordinate, it is natural to return a set of values like (x,y,z). But it seems that we have to take the trouble to create a DTO purely to serve as the return type. Is there a simpler approach?
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you try to return a Map ?

Exemple :
Map<String, String> myResult= new HashMap<String, String>();
myResult.put("x", "1");
myResult.put("y", "2");
myResult.put("z", "3");
return myResult;

David Gimelle
J2EE Developer
http://getj2ee.over-blog.com
 
Marshal
Posts: 58382
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Creating a new class for a return type may appear cumbersome, but it is probably better design. If you are returning coordinates, then a Coordinates class with private x, y, and z fields is a good way to do it. It also makes it obvious to the user what your method returns, making client code easier to design.
 
Campbell Ritchie
Marshal
Posts: 58382
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and welcome to the Ranch, David
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!