Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList size with empty element []

Tags:

java

arraylist

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?

like image 322
Rui Huang Avatar asked Jan 06 '15 20:01

Rui Huang


People also ask

How do you check an ArrayList is empty or not in Java?

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.

Is an empty ArrayList null?

No. An ArrayList can be empty (or with nulls as items) an not be null.

How do I find the size of an ArrayList?

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.


1 Answers

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.

like image 67
Makoto Avatar answered Oct 10 '22 08:10

Makoto