title: How to move contents of one ArrayList to another?
body: <p>Is there a way to move the entire contents of an ArrayList to another instance of ArrayList in O(1)?</p>
  
  <p>I.e.: only the reference to the backing array is passed from one instance to the other (elements are not copied one by one).</p>
  
  <p>For example:</p>
  
  <pre><code>ArrayList&lt;String&gt; a = new ArrayList&lt;&gt;(Arrays.asList("A", "B", "C"));
  ArrayList&lt;String&gt; b = new ArrayList&lt;&gt;();
  a.moveContentsTo(b);
  // 'a' is now empty, while 'b' contains everything that 'a' did before and 'a != b'
  // It is desired that the 'moveContentsTo' method is O(1)
  </code></pre>
  
  <p>Even better, is there an <code>ArrayList#swapContents(ArrayList)</code> method?</p>
  
  <hr>
  
  <p><strong>Further explanation and use-case</strong>: </p>
  
  <p><em>Further explanation</em> 1: the references of 'a' and 'b' must not be exchanged. I am not looking for <code>tmp = a; a = b; b = tmp;</code> type of solutions.</p>
  
  <p><em>Further explanation</em> 2: The operation must be ~O(1) in time.</p>
  
  <p><em>The use-case</em>: This is useful when an object wants to encapsulate a list constructed outside:</p>
  
  <pre><code>public class A {
      private ArrayList&lt;String&gt; items = new ArrayList&lt;&gt;();
  
      /**
       * This method takes the sole ownership of the contents. Whoever
       * passed the list from the outside will not be able to modify
       * contents of 'this.items' from outside the class.
       */ 
      public AnImmutableObject(ArrayList&lt;String&gt; items) {
          if (items != null) {
              items.moveContentsTo(this.items);
          }
      }
  
      /**
       * Other collections that do not provide the 'move' functionality
       * must be copied. If we just stored the reference to 'items' we
       * would break encapsulation as whoever called the constructor
       * still have write capabilities to the collection.
       */ 
      public A(Collection&lt;String&gt; items) {
          if (items != null) {
              this.items.addAll(items);
          }
      }
  
      public List&lt;String&gt; getItems() {
          return Collections.unmodifiableList(items);
      }
  }
  </code></pre>
  
  <p>Notice that we want to avoid making a copy (to increase speed and decrease memory usage). The crucial bit is that the callee must lose the ability to modify the (now encapsulated) <code>ArrayList</code>.</p>