While i was writing code for an accounting application , i observed unusual behavior of List in java. After executing below code,
List<String> accountsList = new ArrayList<String>();
for(int i=0; i< (Integer.MAX_VALUE+2) ;i++){
accountsList.add("Account #"+i);
}
System.out.println("# of accounts in list : "+accountsList.size());
got output as - # of accounts in list : 0
, which was very interesting. Also code ran correctly without throwing any exception. If this is because of value overflow of int, why did not java throw warning/ exception.
Then i modified condition in for loop as, for(int i=0; i< Integer.MAX_VALUE ;i++)
and code worked as expected.
Is this behavior has to do anything with Max value of int, as ArrayList can hold values till count of Integer.MAX_VALUE ( accountsList.size() returns value of type int, and int has max value defined).