In addition to arshaji's answer, I wanted to know if there was a performance advantage when using size() in a loop and saving it in advance. I believe that the result shows that the compiler does optimization and access to the length of the list is the same as accessing the variable (I was worried that the fact that it had to go through the function would slow everything down).
Here is the time it takes for these two for different loop methods:
for(long i = 0 ; i < mylist.size(); i++){} VS for(long i = 0 ; i < 10_000_000; i++){}
Here is the result for a list of ten million items:
fixed length: ,162,157,151,157,156,159,157,149,150,170,158,153,152,158,151,151,156,156,151,153 getSize: ,164,156,159,154,151,160,162,152,154,152,151,149,168,156,152,150,157,150,156,157 import java.util.ArrayList; import java.util.List; public class Main { final static int LENGTH_SAMPLE = 20; final static long LENGTH = 10_000_000; public static void main(String[] args) { List<Long> mylist = new ArrayList<>(); for(long i = 0 ; i < LENGTH; i++){ mylist.add(i); } System.out.println("fixed length:"); for(int i = 0 ; i < LENGTH_SAMPLE; i++){ System.out.printf("," + fixedSize(mylist)); } System.out.println(""); System.out.println("getSize:"); for(int i = 0 ; i < LENGTH_SAMPLE; i++){ System.out.printf("," + fctSize(mylist)); } } private static long fixedSize(List list){ long start = System.currentTimeMillis(); for(long i = 0 ; i < LENGTH; i++){ System.currentTimeMillis(); } return System.currentTimeMillis() - start; } private static long fctSize(List list){ long start = System.currentTimeMillis(); for(long i = 0 ; i < list.size(); i++){ System.currentTimeMillis(); } return System.currentTimeMillis() - start; } }