How to return multiple objects from a Java method?

前端 未结 25 3602
眼角桃花
眼角桃花 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条回答
  •  猫巷女王i
    2020-11-22 00:32

    Alternatively, in situations where I want to return a number of things from a method I will sometimes use a callback mechanism instead of a container. This works very well in situations where I cannot specify ahead of time just how many objects will be generated.

    With your particular problem, it would look something like this:

    public class ResultsConsumer implements ResultsGenerator.ResultsCallback
    {
        public void handleResult( String name, Object value )
        {
            ... 
        }
    }
    
    public class ResultsGenerator
    {
        public interface ResultsCallback
        {
            void handleResult( String aName, Object aValue );
        }
    
        public void generateResults( ResultsGenerator.ResultsCallback aCallback )
        {
            Object value = null;
            String name = null;
    
            ...
    
            aCallback.handleResult( name, value );
        }
    }
    

提交回复
热议问题