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
?