time complexity or hidden cost of .length in java

后端 未结 5 1321
失恋的感觉
失恋的感觉 2020-12-06 11:03

I was looking at a project in java and found a for loop which was written like below:

for(int i=1; i

        
5条回答
  •  抹茶落季
    2020-12-06 11:05

    in java arrays are fixed. Once you declare it you can not change that array's size in memory (if you tried to change the array size it will make a new array in memory).

    Because of this we get O(1) length lookup. As we know the total size in memory of the array. If we also look up the size in memory of the first index we can do a quick calculation to get length at O(1) speed. As no matter how big our array is, its going take the same amount of time to lookup the size in memory and lookup the first index's size

提交回复
热议问题