Array Length in Java

前端 未结 16 1387
忘了有多久
忘了有多久 2020-11-30 21:27

I declared an array as shown below:

int[] arr = new int[10];

Then I assigned following values to the array:

arr[0] = 1;
arr         


        
相关标签:
16条回答
  • 2020-11-30 22:20

    It contains the allocated size, 10. The unassigned indexes will contain the default value which is 0 for int.

    0 讨论(0)
  • 2020-11-30 22:20

    Arrays are static memory allocation, so if you initialize an array of integers:

    int[] intArray = new int[15];
    

    The length will be always 15, no matter how many indexes are filled.

    And another thing, when you intialize an array of integers, all the indexes will be filled with "0".

    0 讨论(0)
  • 2020-11-30 22:21

    Java arrays are actually fixed in size, and the other answers explain how .length isn't really doing what you'd expect. I'd just like to add that given your question what you might want to be using is an ArrayList, that is an array that can grow and shrink:

    https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

    Here the .size() method will show you the number of elements in your list, and you can grow this as you add things.

    0 讨论(0)
  • 2020-11-30 22:23

    First of all, length is a property, so it would be arr.length instead of arr.length().

    And it will return 10, the declared size. The elements that you do not declare explicitely are initialized with 0.

    0 讨论(0)
提交回复
热议问题