Skip to main content

APIzation: Replication Package

[Q#5237261][A#5237354] How to test List<String> for empty or nullness?

https://stackoverflow.com/q/5237261

It seems no matter what I do I get the wrong result. My list is defined as follows: Nothing odd or fancy on the getter/setter: In a session bean I want to alter a different List based on the contents (or lack thereof) of this list. Here is that code: It always falls through to NOT NULL and adds the string to restrictList. It's making me crazy! How do I detect nothingness in this list? Here is the log snippet

Answer

https://stackoverflow.com/a/5237354

You can get the result that you're seeing if the list contains a single zero-length string:

APIzation

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

System.out.println("blah = " + list);  // displays "blah = []"
if (list.isEmpty()) {
    System.out.println("Empty"); // doesn't get displayed
}
package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.List;

public class Human5237354 {

  public static boolean isListOfStringsEmptyOrNullness(List<String> list) {
    System.out.println("blah = " + list); // displays "blah = []"
    if (list.isEmpty()) {
      System.out.println("Empty"); // doesn't get displayed
    }
    return list.isEmpty();
  }
}

package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.List;

/**
 * How to test List<String> for empty or nullness?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/5237354">https://stackoverflow.com/a/5237354</a>
 */
public class APIzator5237354 {

  public static void testList(List<String> list) throws Exception {
    // displays "blah = []"
    System.out.println("blah = " + list);
    if (list.isEmpty()) {
      // doesn't get displayed
      System.out.println("Empty");
    }
  }
}