I have one ArrayList, for some reason i have to add empty string element "":
ArrayList<String> rList = new ArrayList<String>();
rList.add("");
When I read the size of the array list rList then, rList.size() == 1 and rList.isEmpty() == false.
How can I check this kind of array list? does the empty element cause the size equals 1 and not empty?
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.
No. An ArrayList can be empty (or with nulls as items) an not be null.
The size of an ArrayList can be obtained by using the java. util. ArrayList. size() method as it returns the number of elements in the ArrayList i.e. the size.
Even though you're adding an empty string to your list, you're still adding something to the list. And, that's what counts.
The data may be empty (or even null
, as an ArrayList
will allow you to insert null
), but the size will increase (and the list won't be empty).
Now, if you only want to check that there's just that sort of element in your list (as you state in comments), then that's possible like this:
if(rList.size() == 1 && "".equals(rList.get(0)) {
// perform work
}
The line above will only succeed if there's just one entry in the list, and only if it's the empty string. The reverse of the string literal and get
is to guard against a NullPointerException
, as that can occur if you have it flipped the other way 'round, and there's null
in for element 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With