Java examples for Collection Framework:Array Element
Checks if the specified collection/array/iterator is empty.
//package com.java2s; import java.lang.reflect.Array; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; public class Main { public static void main(String[] argv) { Object object = "java2s.com"; System.out.println(sizeIsEmpty(object)); }/*from w ww. jav a2 s . com*/ /** * Checks if the specified collection/array/iterator is empty. * <p> * This method can handles objects as follows * <ul> * <li>Collection - via collection isEmpty * <li>Map - via map isEmpty * <li>Array - using array size * <li>Iterator - via hasNext * <li>Enumeration - via hasMoreElements * </ul> * <p> * Note: This method is named to avoid clashing with * {@link #isEmpty(Collection)}. * * @param object * the object to get the size of, not null * @return true if empty * @throws IllegalArgumentException * thrown if object is not recognised or null */ public static boolean sizeIsEmpty(Object object) { if (object instanceof Collection) { return ((Collection<?>) object).isEmpty(); } else if (object instanceof Map) { return ((Map<?, ?>) object).isEmpty(); } else if (object instanceof Object[]) { return ((Object[]) object).length == 0; } else if (object instanceof Iterator) { return !((Iterator<?>) object).hasNext(); } else if (object instanceof Enumeration) { return !((Enumeration<?>) object).hasMoreElements(); } else if (object == null) { throw new IllegalArgumentException( "Unsupported object type: null"); } else { try { return Array.getLength(object) == 0; } catch (IllegalArgumentException ex) { throw new IllegalArgumentException( "Unsupported object type: " + object.getClass().getName()); } } } }