How to get elements of an array that is not null

后端 未结 2 921
我寻月下人不归
我寻月下人不归 2021-01-29 00:19

I am doing gift (String-type) storage, using arrays, with the maximum 500 million. I want to get the number of used elements in an array like how many gifts are currently in sto

2条回答
  •  离开以前
    2021-01-29 00:58

    You can iterate through the array and count the initialized array elements.

    int counter = 0;
    for (int i = 0; i < arrayName.length; i ++)
        if (arrayName[i] != null)
            counter ++;
    

    Also it would be even better if you used ArrayList so you could use size()

    ArrayList arrayName = new ArrayList(20);
    System.out.println(arrayName.size());
    

    It will print 0, as there are no elements added to the ArrayList.

提交回复
热议问题