본문 바로가기

Programming!

guava의 Iterables.isEmpty

java null.. lib들을 사용하다보면 어떤 놈들은 null처리가 되어 있는 놈들이 있는가 하면, 그냥 null exception 을 내뱉는 놈들도 있다.

가령 guava의 Iterables.isEmpty(Iterable..)를 무심결에 썼는데 nullpointerexception 을 내뱉에 버린다.

  /**
   * Determines if the given iterable contains no elements.
   *
   * <p>There is no precise {@link Iterator} equivalent to this method, since
   * one can only ask an iterator whether it has any elements <i>remaining</i>
   * (which one does using {@link Iterator#hasNext}).
   *
   * @return {@code true} if the iterable contains no elements
   */
  public static boolean isEmpty(Iterable<?> iterable) {
    if (iterable instanceof Collection) {
      return ((Collection<?>) iterable).isEmpty();
    }
    return !iterable.iterator().hasNext();
  }


헌데, spring이나 commons의 CollectionUtils.isEmpty(..)를 쓰면 그냥 true 를 내뱉고.. 그저 잘 판단해서 쓰길 바란다.

    /**
     * Return {@code true} if the supplied Collection is {@code null} or empty.
     * Otherwise, return {@code false}.
     * @param collection the Collection to check
     * @return whether the given Collection is empty
     */
    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }