How to check the sizeof array list in java without get error exception from the compiler if the arraylist is not been initialised.
I have tried the following but it does not work. and I got this message:
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
ArrayList<String> str = new ArrayList<>();
if (str.size()>0)
There is nothing in the code you posted that would throw an
IndexOutOfBoundsException. I assume you were callingstr.get(0)without the size check before?Anyway, your code is fine, i.e. you should be able to extend it to do something like the following:
However, for cleanliness I would suggest using
if (!someStrings.isEmpty())instead, which checks the same thing asif (someStrings.size() > 0).