Finding size i.e. number of non-null elements stored in array in Java

DPKGRG :

Purpose : Array.length 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.

Since ArrayList has a size() method which gives us count of actual elements stored regardless of total storage initialized.

So, I thought of converting array to ArrayList and finding out the size. Hence I used Arrays.asList(a).size() as shown below:

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() );
    }

Strangely , it returns result as 1 regardless of the a[0], a[1], a[2].

Same steps if we do with ArrayList instead of Array gives us result 3:

{
    List<Integer> temp = new ArrayList<Integer>(20); 
    System.out.println(temp.size()); 
    temp.add(20); 
    temp.add(40); 
    System.out.println(temp.size()); 
}

Result is 0 2.

Question: Should be agree that something is wrong with asList API of Arrays utitlity like bug or limitation?

Remarks: Looking at internal implementation, I understand that asList invokes constructor of ArrayList:

  public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        .....
  }

It again invokes the collection's toArray. But then not sure why we are getting answer as 1 since elementData.length should have stored in size value 10?

mangusta :

You get 1 because Arrays.asList(int[] a) returns List<int[]>, not List<Integer>. The way you're using method asList() is incorrect. If you would like to get List<Integer> instead, you should pass the contents of array to method asList() one by one.
List<Integer> list = Array.asList(30, 100, 33);
There is no direct method to convert an array into List on the fly

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94975&siteId=1