集册 Java实例教程 检查指定的collection/array/iterator是否为空。

检查指定的collection/array/iterator是否为空。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

1067
检查指定的collection/array/iterator是否为空。


//package com.nowjava;
/**
 * 时 代 J a v a 提 供 
**/

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 = "nowjava.com";

        System.out.println(sizeIsEmpty(object));

    }//来自 时   代     Java  公  众  号 - nowjava.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")
展开阅读全文