Using collection size in for loop comparison

后端 未结 4 774
你的背包
你的背包 2020-12-01 21:55

Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

for(int i=0;i

        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 22:30

    Calling the size() method of a collection is just returning an integer value that is already kept track of. There isnt much of a time difference because size() isnt actually counting the number of items but instead the number of items are kept track of when you add or remove them.

提交回复
热议问题