如何测试List <string>是否为空或为null?</string>

时间:2011-03-08 19:26:44

标签: java

无论我做什么,我都会得到错误的结果。

我的清单定义如下:

private List<String> selectedPriorities;

getter / setter没什么奇怪或奇特的东西:

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

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

在会话bean中,我想根据此列表的内容(或缺少内容)更改不同的列表。

以下是代码:

List<String> restrictList = new ArrayList<String>();
restrictList.add("lower(logs.clazz) like lower(concat(#{logs.clazz},'%'))");
restrictList.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})");

它总是落到NOT NULL并将字符串添加到restrictList。它让我疯了!如何在此列表中检测到虚无?这是日志片段

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

2 个答案:

答案 0 :(得分:11)

如果列表包含单个零长度字符串,您可以获得结果:

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
}

答案 1 :(得分:-3)

可能是因为

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

需要回报吗?