Get size of Collection and NullPointerException safe - Java java.util

Java examples for java.util:Collection Null Element

Description

Get size of Collection and NullPointerException safe

Demo Code

import java.util.Collection;

public class Main {
  public static void main(String[] argv) {
    Collection collection = java.util.Arrays.asList("asdf", "book2s.com");
    System.out.println(getSize(collection));
  }//from   w w  w . j a va 2 s.  c om

  /**
   * * Get size of Collection and NullPointerException safe
   *
   * @param collection
   * @return -1 if collction is null then else return collection's size
   */
  public static int getSize(Collection collection) {
    if (collection == null) {
      return -1;
    }
    return collection.size();
  }
}

Related Tutorials