"Is there a basic Java Set implementation that does not permit nulls?"에 대한 후속 질문입니다. (답변에 도움을 준 모든 분들께 감사드립니다)집합에 추가하기 전에 null에 대한 Collection을 검사하는 여러 가지 방법에 대한 장단점은 무엇입니까?
Sun은이 OOTB와 같은 간단한 것을 제공하지 않았기 때문에이를 수행하는 방법은 래퍼/프록시를 사용하는 것 같습니다. 이것은 거의 똑바로 보인다. 내가 궁금해하는 점은 컬렉션을 추가하는 다음 두 가지 접근 방식의 장점/단점은 무엇입니까? 아니면 더 나은 접근 방식이 있습니까? 사전에
접근 # 1
public boolean addAll(Collection<? extends E> c) {
if (null == c) {
throw new NullPointerException("c cannot be null");
}
/*
* This seems like a terrible abuse of exceptions when
* all I want to do is check the set for a null.
*
* However, simply running through each element of the
* Collection may provide much worse performance for large
* collections. And according to the Collection API, the
* contains method may throw NullPointerExceptions if the
* collection implementation does not allow null elements.
*/
boolean collectionContainsNull = false;
try {
collectionContainsNull = c.contains(null);
} catch (NullPointerException safeToIgnore) {
/* Safe to ignore since we do not want nulls */
}
if (collectionContainsNull) {
throw new NullPointerException("c cannot contain null elements");
}
this.wrapperSet.addAll(c);
}
접근 # 2
public boolean addAll(Collection<? extends E> c) {
if (null == c) {
throw new NullPointerException("c cannot be null");
}
E[] a = (E[])c.toArray();
/*
* We have to iterate through the entire collection to check for
* a null. This won't take advantage of any optimizations that
* c.contains may be using.
*
* We don't call add(e) here because if we hit a null midway through
* we would violate the condition that the set remains unchanged
* on error.
*/
for (E e : a) {
if (null == e) {
throw new NullPointerException("c cannot contain nulls");
}
}
this.wrapperSet.addAll(a);
}
감사합니다!
toArray의 의도 장점은, 원래의 콜렉션이 수표 나에 대한 후속 호출 중 하나 중에 수정되는 경우 있음 addAll은 문제가되지 않습니다. –