title: Finding size i.e. number of non-null elements stored in array in Java
body: <p><strong>Purpose :</strong> <code>Array.length</code> gives us storage initialized to array. But wanted to find out count of non-null elements stored in array out of total storage initialized. I know many approaches are possible but here question is related to approach which I used.</p>
  
  <p><em>Since <code>ArrayList</code> has a <code>size()</code> method which gives us count of actual elements stored regardless of total storage initialized.</em></p>
  
  <p>So, I thought of converting array to <code>ArrayList</code> and finding out the size. Hence I used <code>Arrays.asList(a).size()</code> as shown below:</p>
  
  <pre><code>public class Driver {
  
      public static void main(String []args)
      {
          int a[] = new int[10];
          a[0]=30;
          a[1]=100;
          a[2]=33;
          System.out.println((Arrays.asList(a)).size() );
      }
  </code></pre>
  
  <p>Strangely , it returns result as 1 regardless of the <code>a[0]</code>, <code>a[1]</code>, <code>a[2]</code>.</p>
  
  <p>Same steps if we do with <code>ArrayList</code> instead of Array gives us result 3:</p>
  
  <pre><code>{
      List&lt;Integer&gt; temp = new ArrayList&lt;Integer&gt;(20); 
      System.out.println(temp.size()); 
      temp.add(20); 
      temp.add(40); 
      System.out.println(temp.size()); 
  }
  </code></pre>
  
  <p>Result is <code>0 2</code>.</p>
  
  <p><strong>Question:</strong> Should be agree that something is wrong with <code>asList</code> API of <code>Arrays</code> utitlity like bug or limitation? </p>
  
  <p><strong>Remarks:</strong>
  Looking at internal implementation, I understand that <code>asList</code> invokes constructor of <code>ArrayList</code>:</p>
  
  <pre><code>  public ArrayList(Collection&lt;? extends E&gt; c) {
          elementData = c.toArray();
          size = elementData.length;
          .....
    }
  </code></pre>
  
  <p>It again invokes the collection's <code>toArray</code>. But then not sure why we are getting answer as 1 since <code>elementData.length</code> should have stored in size value <code>10</code>? </p>