Returns the size of the collection if it can be determined to be a collection - Java java.util

Java examples for java.util:Collection Attribute

Description

Returns the size of the collection if it can be determined to be a collection

Demo Code


//package com.java2s;
import java.lang.reflect.Array;

import java.util.Collection;

import java.util.Map;

import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) {
        Object value = "java2s.com";
        System.out.println(size(value));
    }//w  w  w . jav  a 2  s .  c  om

    /**
     * Returns the size of the collection if it can be determined to be a collection
     *
     * @param value the collection
     * @return the size, or <tt>null</tt> if not a collection
     */
    public static Integer size(Object value) {
        if (value != null) {
            if (value instanceof Collection) {
                Collection<?> collection = (Collection<?>) value;
                return collection.size();
            } else if (value instanceof Map) {
                Map<?, ?> map = (Map<?, ?>) value;
                return map.size();
            } else if (value instanceof Object[]) {
                Object[] array = (Object[]) value;
                return array.length;
            } else if (value.getClass().isArray()) {
                return Array.getLength(value);
            } else if (value instanceof NodeList) {
                NodeList nodeList = (NodeList) value;
                return nodeList.getLength();
            }
        }
        return null;
    }
}

Related Tutorials