自我总结,有什么不到位的地方,请各位纠正补充,感激不尽!
目的:使程序更严谨
***对象验证是否不为空: if( null != obj )
***List验证不为空:if( null != list && list.size() > 0 )
***Map验证不为空:if( null != map && map.size() > 0 )
好了,废话不多说,上代码
实体类Student(随便起一个)
package com.core.test; public class Student { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
测试类CollectionTest
package com.core.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CollectionTest { public static void main(String[] args) { Student stu = new Student(); System.out.println("student对象-->" + stu); List<Student> stuList = new ArrayList<Student>(); if (null != stuList && stuList.size() > 0) { System.out.println("student list不为空"); } else { System.out.println("student list为空"); } System.out.println("student list-->" + stuList); // Map<String,Object> map = null; Map<String, Object> map = new HashMap<String, Object>(); // map.put("stu", stu); if (null != map && map.size() > 0) { System.out.println("map 不为空"); } else { System.out.println("map 为空"); } System.out.println("map集合-->" + map); } }
结果:
student对象-->com.core.date.Student@340d1fa5 student list为空 student list-->[] map 为空 map集合-->{}
总结:集合判断非空除了要验证是否为null,还要验证size是否大于0