How to return multiple objects from a Java method?

前端 未结 25 3130
眼角桃花
眼角桃花 2020-11-21 23:55

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap<

25条回答
  •  故里飘歌
    2020-11-22 00:29

    Before Java 5, I would kind of agree that the Map solution isn't ideal. It wouldn't give you compile time type checking so can cause issues at runtime. However, with Java 5, we have Generic Types.

    So your method could look like this:

    public Map doStuff();
    

    MyType of course being the type of object you are returning.

    Basically I think that returning a Map is the right solution in this case because that's exactly what you want to return - a mapping of a string to an object.

提交回复
热议问题