Best practice to validate null and empty collection in Java

后端 未结 9 2017
北海茫月
北海茫月 2020-12-12 10:57

I want to verify whether a collection is empty and null. Could anyone please let me know the best practice.

Currently, I am checking as below:



        
9条回答
  •  情歌与酒
    2020-12-12 11:32

    When you use spring then you can use

    boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
    

    where obj is any [map,collection,array,aything...]

    otherwise: the code is:

    public static boolean isEmpty(Object[] array) {
        return (array == null || array.length == 0);
    }
    
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
    
        if (obj.getClass().isArray()) {
            return Array.getLength(obj) == 0;
        }
        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length() == 0;
        }
        if (obj instanceof Collection) {
            return ((Collection) obj).isEmpty();
        }
        if (obj instanceof Map) {
            return ((Map) obj).isEmpty();
        }
    
        // else
        return false;
    }
    

    for String best is:

    boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
    

提交回复
热议问题