Rui Huang
Rui Huang

Reputation: 382

Java ArrayList size with empty element []

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?

Upvotes: 5

Views: 29107

Answers (4)

Salahin Rocky
Salahin Rocky

Reputation: 435

To check empty list use this code: Even list size 1 but its get() method return null. so that you can ensure that actually list have no value.

if(someList.get(0)!=null)

Upvotes: 2

Drew Kennedy
Drew Kennedy

Reputation: 4168

To answer your question How can I check this kind of array list?, you can check the indices to see if your ArrayList contains any particular value by iterating through it.

ArrayList<String> rList = new ArrayList<String>();
rList.add("");

for (String item : rList) {
    if (item.equals("")) {
        //do something
    }
}

If you're checking if all indices of your ArrayList are empty Strings, one way is to add a counter and compare it to the size of the ArrayList.

ArrayList<String> rList = new ArrayList<String>();
rList.add("");
rList.add("");
rList.add("");

int crossCheck = 0;

for (String item : rList) {
    if (item == null) {//equals() will throw a NPE when checking for null values
        //do something
    } else if (item.isEmpty()) {
        crossCheck++;
        //do something
    }
}
//both are 3 in this case
if (rList.size() == crossCheck) {
    //all indices are empty Strings
}

Makoto has an excellent answer for the rest of your question.

Upvotes: 0

Makoto
Makoto

Reputation: 106400

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.

Upvotes: 11

Hajmola
Hajmola

Reputation: 93

To check whether a String is empty: String x =""; boolean isXEmpty = x.isEmpty();

Yes, the empty String instance is a valid instance as any other String. So it will count.

Upvotes: 2

Related Questions