开发者

How to test List<String> for empty or nullness?

It seems no matter what I do I get the wrong result.

My list is defined as follows:

private List<String> selectedPriorities;

Nothing odd or fancy on the getter/setter:

public void setSelectedPriorities(List<String> selectedPriorities) {
    this.selectedPriorities = selectedPriorities;
}

public List<String> getSelectedPriorities() {
    return selectedPriorities;
}

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:

List<String> restrictList = new ArrayList<String>();
restrictList.add("lower(logs.clazz) like lower(concat(#{logs.clazz},'%'))");
res开发者_如何转开发trictList.add("lower(logs.rule) like lower(concat(#{logs.rule},'%'))");
PrioritySelectorBean selectorBean = (PrioritySelectorBean) Component.getInstance("prioritySelectorBean",true);
System.out.println("constructRestrictionList selectorBean "+selectorBean.getSelectedPriorities());

if (selectorBean.getSelectedPriorities() == null) {
    System.out.println("IS NULL");
    return restrictList;
}

if (selectorBean.getSelectedPriorities().isEmpty()){
    System.out.println("IS EMPTY");
}

if (selectorBean.getSelectedPriorities().size()<1){
    System.out.println("HAS NOTHING IN IT");
    return restrictList;
}
System.out.println("NOT NULL");
restrictList.add("lower(logs.priority) in (#{prioritySelectorBean.selectedPriorities})");

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

14:24:10,057 INFO  [STDOUT] constructRestrictionList selectorBean []
14:24:10,057 INFO  [STDOUT] NOT NULL


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

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
}


probably because

if (selectorBean.getSelectedPriorities().isEmpty()){
       System.out.println("IS EMPTY");   
} 

needs a return?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜