Programming

Java에서 null 및 empty 컬렉션의 유효성을 검사하는 모범 사례

procodes 2020. 5. 16. 11:17
반응형

Java에서 null 및 empty 컬렉션의 유효성을 검사하는 모범 사례


컬렉션이 비어 있는지 확인하고 싶습니다 null. 누구든지 모범 사례를 알려주십시오.

현재 다음과 같이 확인하고 있습니다.

if (null == sampleMap || sampleMap.isEmpty()) {
  // do something
} 
else {
  // do something else
}

당신이 사용하는 경우 아파치 코 몬즈 컬렉션 프로젝트의 라이브러리를, 당신은 사용할 수 있습니다 CollectionUtils.isEmptyMapUtils.isEmpty()수집 또는지도 인 경우 각각 확인 방법 또는 널 (null)을 (그들은 "널 안전"입니다 즉).

이 메소드의 코드는 @icza 사용자가 자신의 답변에서 작성한 것입니다.

수행하는 작업에 관계없이 작성하는 코드가 적을수록 코드의 복잡성이 감소함에 따라 테스트해야하는 코드가 줄어 듭니다.


이것이 가장 좋은 방법입니다. 도우미 메소드를 작성하여 수행 할 수 있습니다.

public static boolean isNullOrEmpty( final Collection< ? > c ) {
    return c == null || c.isEmpty();
}

public static boolean isNullOrEmpty( final Map< ?, ? > m ) {
    return m == null || m.isEmpty();
}

Spring 프레임 워크를 사용하는 경우 CollectionUtilsCollections (List, Array) 및 Map 등을 모두 검사 하는 사용할 수 있습니다 .

if(CollectionUtils.isEmpty(...)) {...}

개인적으로 필자는 빈 컬렉션 대신 빈 컬렉션을 사용 null하고 알고리즘의 경우 컬렉션이 비어 있는지 여부에 관계없이 알고리즘이 작동하도록하는 것이 좋습니다.


당신이 봄을 사용하면 다음을 사용할 수 있습니다

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

여기서 obj는 [map, collection, array, aythink ...]입니다.

그렇지 않으면 : 코드는 다음과 같습니다

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;
}

문자열 최고는 다음과 같습니다.

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

null을 확인 해야하는 경우 그 방법입니다. 그러나 이것을 제어 할 수 있다면 가능하면 빈 컬렉션을 반환하고 나중에 비어 있는지 확인하십시오.

이 스레드 는 C #과 거의 동일하지만 원칙은 Java에도 동일하게 적용됩니다. 거기에 언급 된 것처럼 null은 다음과 같은 경우에만 반환해야합니다

  • null은보다 구체적인 것을 의미 할 수 있습니다.
  • your API (contract) might force you to return null.

You can use org.apache.commons.lang.Validate's "notEmpty" method:

Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.


For all the collectionsinclusing map use: isEmpty method which is there on these collection objects. But you have to do a nulkl check before

Map map;

........ if(map!=null && !map.isEmpty()) ......

참고URL : https://stackoverflow.com/questions/12721076/best-practice-to-validate-null-and-empty-collection-in-java

반응형