title: What are the pros and cons for different methods of checking a Collection for a null before adding to a Set?
body: <p>This is a follow up question to "<a href="https://stackoverflow.com/questions/591115/is-there-a-basic-java-set-implementation-that-does-not-permit-nulls">Is there a basic Java Set implementation that does not permit nulls?</a>". (thank you to all of those who helped with the answer) </p>
  
  <p>It seems that the way to do this, since Sun didn't provide something simple like this OOTB, is with a wrapper / proxy. This seems nearly straight forward. What I am wondering is what are the pros/cons of the following two approaches of adding a collection, or is there another better approach?</p>
  
  <p>Approach #1</p>
  
  <pre><code>public boolean addAll( Collection&lt;? extends E&gt; 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);
  }
  </code></pre>
  
  <p>Approach #2</p>
  
  <pre><code>public boolean addAll( Collection&lt;? extends E&gt; 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);
  }
  </code></pre>
  
  <p>Thanks in advance!</p>