go back..

List Contains Null

java list

발생한 오류

public boolean isXXX() {
    return List.of("A", "B").contains(value);
}

원인 파악

  Returns true if this list contains the specified element. 
        More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).
  Params:
  o – element whose presence in this list is to be tested
  Returns:
  true if this list contains the specified element
  Throws:
  ClassCastException – if the type of the specified element is incompatible with this list (optional)
  NullPointerException – if the specified element is null and this list does not permit null elements (optional)
  
          boolean contains(Object o);
    /**
     * Returns an unmodifiable list containing three elements.
     *
     * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
     *
     * @param <E> the {@code List}'s element type
     * @param e1 the first element
     * @param e2 the second element
     * @param e3 the third element
     * @return a {@code List} containing the specified elements
     * @throws NullPointerException if an element is {@code null}
     *
     * @since 9
     */
    static <E> List<E> of(E e1, E e2, E e3) {
        return ImmutableCollections.listFromTrustedArray(e1, e2, e3);
    }

테스트 작성

    @Test
    public void containsNull() {
        List<String> testList = Arrays.asList("A", "B", "C", null);
        assertThat(testList.contains(null)).isEqualTo(true);
    }

    @Test
    public void notContainsNull() {
        List<String> testList = Arrays.asList("A", "B", "C");
        assertThat(testList.contains(null)).isEqualTo(false);
    }
        @Test
    public void immutableList() {
        List<String> testList = List.of("A", "B", "C");
        assertThatThrownBy(() -> testList.contains(null))
                .isInstanceOf(NullPointerException.class);
    }
    
        @Test
    public void immutableListDoesNotAllowNull() {
        assertThatThrownBy(() -> List.of("A", "B", "C", null))
                .isInstanceOf(NullPointerException.class);
    }

© 2026 Hyejin   •  Powered by Soopr   •  Theme  Moonwalk