List 와 null...etc

만년 쭈글이 개발자·2022년 9월 27일
0

TIL

목록 보기
6/13

List를 이용하여 코드를 짜다가 늘 쓰면서도 잘 모른다는 생각이 들어서 의문이 들었던 부분들 위주로 찾아서 대충..정리해보았음 (대충이었는데 쓰다보니 넘 오래걸림 ㅜ)

List?

  • List 는 Collection을 상속하는 interface 이고, List를 구현하는 collections들 에 따라 달라질 수 있음

List와 null

  • list에 null이 들어갈수 있는가?
    가능

  • list의 요소로 null이 카운팅되는가?
    .size() 로 재봤을때 개수에 포함됨

  • 제약조건(notNull)이 있는 list를 생성하기

    Constraints.constrainedList(new ArrayList(), Constraints.notNull())
  • list에 요소를 추가할때 null을 무시하도록

      CollectionUtils.addIgnoreNull(list, element);
      //org.apache.commons.collections4 pakage
          public static <T> boolean addIgnoreNull(final Collection<T> collection, final T object) {
            if (collection == null) {
                throw new NullPointerException("The collection must not be null");
            }
            return object != null && collection.add(object);
        }
  • 리스트에서 null을 제거하기

    //remove 이용
    list.removeAll(Collections.singletonList(null));
    
    //iterator이용
    Iterator it = list.iterator();
    
    while(it.hasNext()){
        if(it.next() == null){
            it.remove();
        }
    }

    나머지 null 삭제 방법들은 아래 링크 참고
    https://www.baeldung.com/java-remove-nulls-from-list

  • NullPointException이 터지는 method들?
    List.of(null)은 불가능

  • 리스트체크유틸(isEmpty(),, CollectionUtils.isEmpty())

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

Collections EmptyList의 차이

  • EMPTY_LIST
        /**
         * The empty list (immutable).  This list is serializable.
         *
         * @see #emptyList()
         */
        @SuppressWarnings("rawtypes")
        public static final List EMPTY_LIST = new EmptyList<>();
  • emptyList()
        /**
         * Returns an empty list (immutable).  This list is serializable.
         *
         * <p>This example illustrates the type-safe way to obtain an empty list:
         * <pre>
         *     List<String> s = Collections.emptyList();
         * </pre>
         *
         * @param <T> type of elements, if there were any, in the list
         * @return an empty immutable list
         *
         * @see #EMPTY_LIST
         * @since 1.5
         */
        @SuppressWarnings("unchecked")
        public static final <T> List<T> emptyList() {
            return (List<T>) EMPTY_LIST;
        }
    코드를 보면 emptyList()가 형변환 처리를 한번 더 해주고 있음 그 처리로 인해 좀더 type-safe한 emptyList를 얻을 수 있다. javadoc에도 아래처럼 쓰여있음
    This example illustrates the type-safe way to obtain an empty list
    -> 결론 : emptyList()를 쓰는편이 안전하니 대부분은 이걸 쓰는 편이 좋다

참고 :https://codechacha.com/ko/java-check-if-list-empty/

profile
오늘의 나는 내일의 나보다 젊지

0개의 댓글