javamethodsreturn-valueargument-passing

JAVA Returning an object or pass by reference


Here a beginners question.

Is there any difference in JAVA between passing an object as argument to a method or returning that object from the method. For instance: Is it better to pass a List as an argument and fill it in the method or just allow the method to return a list?

My guess is that it should be no difference since a reference is returned and nothing is copied. But is there something more subtle behind?

thanks in advance

Altober


Solution

  • First, there is no "pass by reference" in Java: the language is passing references by value (it is not the same thing).

    The answer to your question is "it depends": passing an object as an argument to a method lets you reuse the same object in multiple invocations, while returning an object forces the method to supply a new or an existing object to the caller.

    Consider this example: you are collecting data from several methods, and you need to put all the data in one list. You can have methods returning lists with their data

    interface DataSource {
        void supplyData(List<Data> list);
    }
    

    or you could pass these methods a list, and have them add their data to the same list:

    interface DataSource {
        List<Data> supplyData(); 
    }
    

    In the first case, you could loop through multiple data sources, passing them the same list:

    List<Data> bigList = new ArrayList<Data>();
    foreach (DataSource s : mySources) {
        s.supplyData(bigList);
    }
    

    In the second case, you would need to get individual lists from the calls of supplyData, and put their content in a big list that you keep in your loop:

    List<Data> bigList = new ArrayList<Data>();
    foreach (DataSource s : mySources) {
        List<Data> tmp = s.supplyData();
        bigList.addAll(tmp);
    }
    

    In the second case each invocation creates a temporary list tmp that gets discarded after its content is added to the big list.

    Note that passing an existing list is not necessarily a better solution - in fact, there are situations when you should avoid that.

    For example, when you deal with externally supplied plug-ins, you should prefer the second strategy. Otherwise, a malicious implementation of the DataSource interface would be able to manipulate the common list in ways not expected by your program, such as adding its items ahead of everyone else's, removing items that came from other sources, examining items from other sources, and so on.