title: Alternatives to pass-by-reference updates on list in Java
body: <p>I have a class that has one or more input list and it needs to process and update other lists which are scoped outside of the class. What can be a good pattern to use here?
  I've tried the following two patterns here:</p>
  <ol>
  <li>Update directly by using pass-by-reference</li>
  <li>Using callbacks to let the caller handle how they want to deal with the update</li>
  </ol>
  <p><strong>Examples</strong></p>
  <ol>
  <li>Using direct update</li>
  </ol>
  <pre class="lang-java prettyprint-override"><code>public class SomeClass {
    public void process(List&lt;String&gt; inputList, List&lt;StringContainer&gt; errorContainerList, List&lt;String&gt; validList) {
      for (String str : inputList) {
        if (someCondition) {
          validList.add(str);
        } else {
          errorContainerList.add(new StringContainer(str, new SomeError()));
        }
      }
    }
  }
  
  void someCaller(List&lt;String&gt; inputList) {
      List&lt;String&gt; validList = new ArrayList&lt;&gt;();
      List&lt;StringContainer&gt; errorContainerList = new ArrayList&lt;&gt;();
  
      SomeClass obj = new SomeClass();
      obj.process(inputList, errorContainerList, validList);
  
      // Similarly,
      validList.remove(...);
      errorContainerList.add(...);
  }
  </code></pre>
  <ol start="2">
  <li>Using callbacks</li>
  </ol>
  <pre class="lang-java prettyprint-override"><code>public interface StringErrorHandler {
      void handle(String str, SomeError error);
  }
  
  public interface ValidInputHandler {
      void handle(String str);
  }
  
  public class SomeClass {
    public void process(List&lt;String&gt; inputList, StringErrorHandler errorHandler, ValidInputHandler validInputHandler) {
      for (String str : inputList) {
        if (someCondition) {
          validInputHandler.handle(str);
        } else {
          errorHandler.handle(str, new SomeError());
        }
      }
    }
  }
  
  void someCaller(List&lt;String&gt; inputList) {
      List&lt;String&gt; validList = new ArrayList&lt;&gt;();
      List&lt;StringContainer&gt; errorContainerList = new ArrayList&lt;&gt;();
  
      SomeClass obj = new SomeClass();
      obj.process(inputList, new StringErrorHandler() {
          
          @Override
          public void handle(String str, SomeError error) {
              errorContainerList.add(new StringContainer(str, error));
          }
      }, new ValidInputHandler() {
          
          @Override
          public void handle(String str) {
              validList.add(str);
          }
      });
  
      // Similarly,
      validList.remove(...);
      errorContainerList.add(...);
  }
  </code></pre>