title: How to properly return part of ArrayList in Java?
body: <p>I have a class <code>SomeClass</code> with a static member <code>myMap</code> <code>enter code here</code>that has the form <code>HasmMap&lt;String,ArrayList&lt;SomeOtherClass&gt;&gt;</code> which gets de-serialized from a file.</p>
  
  <p>I have a method</p>
  
  <pre><code>public ArrayList&lt;SomeOtherClass&gt; getList(final String key, final int N)
  </code></pre>
  
  <p>that is supposed to lookup <code>key</code> in the map and return the first <code>N</code> elements of the corresponding <code>ArrayList</code>, or the whole thing if the list has <code>&lt;= N</code> elements. How should I implement the <code>TODO</code> line below:</p>
  
  <pre><code>public ArrayList&lt;SomeOtherClass&gt; getList(final String key, final int N)
  {
      ArrayList&lt;SomeOtherClass&gt; arr = myMap.get(key);
      if (arr == null) return null;
  
      if (arr.size() &lt;= N)
      {
         return arr;
      }
      else
      {
         // TODO: return first N elements
      }
  }
  </code></pre>
  
  <p>to do it efficiently, i.e. without creating unneeded copies in memory while actually returning the right data?</p>