Difference between size and length methods?

前端 未结 6 646
北海茫月
北海茫月 2020-12-12 14:46

What is the difference between .size() and .length ? Is .size() only for arraylists and .length only for arrays?

6条回答
  •  遥遥无期
    2020-12-12 15:11

    length is constant which is used to find out the array storing capacity not the number of elements in the array

    Example:

    int[] a = new int[5]
    

    a.length always returns 5, which is called the capacity of an array. But

    number of elements in the array is called size

    Example:

    int[] a = new int[5]
    a[0] = 10
    

    Here the size would be 1, but a.length is still 5. Mind that there is no actual property or method called size on an array so you can't just call a.size or a.size() to get the value 1.

    The size() method is available for collections, length works with arrays in Java.

提交回复
热议问题