Array Length in Java

前端 未结 16 1388
忘了有多久
忘了有多久 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:16

    If you want the logical size of the array, you can traverse all the values in the array and check them against zero. Increment the value if it is not zero and that would be the logical size. Because array size is fixed, you do not have any inbuilt method, may be you should have a look at collections.

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

    if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

    0 讨论(0)
  • Arrays are allocated memory at compile time in java, so they are static, the elements not explicitly set or modified are set with the default values. You could use some code like this, though it is not recommended as it does not count default values, even if you explicitly initialize them that way, it is also likely to cause bugs down the line. As others said, when looking for the actual size, ".length" must be used instead of ".length()".

    public int logicalArrayLength(type[] passedArray) {
        int count = 0;
        for (int i = 0; i < passedArray.length; i++) {
            if (passedArray[i] != defaultValue) {
                count++;
            }
        }
        return count;
    }
    
    0 讨论(0)
  • 2020-11-30 22:17

    It should be:

    int a = arr.length;
    

    Parenthesis should be avoided.

    0 讨论(0)
  • 2020-11-30 22:18
    int[] arr = new int[10];
    

    arr is an int type array which has size 10. It is an array of 10 elements. If we don't initialize an array by default array elements contains default value. In case of int array default value is 0.

    length is a property which is applicable for an array.
    here arr.length will give 10.

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

    It will contain the actual size of the array as that is what you initialized the array to be when you declared it. Java has no concept of the "logical" size of an array, as far as it is concerned the default value of 0 is just as logical as the values you have manually set.

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