assert Collection Size - Java java.util

Java examples for java.util:Collection Size

Description

assert Collection Size

Demo Code


//package com.java2s;
import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        int size = 42;
        assertSize(collection, size);/*from  w w w.  j a v a2s. c  o m*/
    }

    /**
     *
     * @param collection
     * @param size
     */
    public static void assertSize(Collection<?> collection, int size) {
        assertNotEmpty(collection);
        if (collection.size() != size) {
            throw new IllegalArgumentException(
                    "'collection' must be of size " + size + " was "
                            + collection.size());
        }
    }

    public static void assertSize(Object[] array, int size) {
        assertNotEmpty(array);
        if (array.length != size) {
            throw new IllegalArgumentException("'array' must be of size "
                    + size + " was " + array.length);
        }
    }

    /**
     *
     * @param collection
     */
    public static void assertNotEmpty(Collection<?> collection) {
        if (collection == null || collection.size() == 0) {
            throw new IllegalArgumentException(
                    "'collection' must not be null or empty");
        }
    }

    /**
     *
     * @param array
     */
    public static void assertNotEmpty(Object[] array) {
        if (array == null || array.length == 0) {
            throw new IllegalArgumentException(
                    "'array' must not be null or empty");
        }
    }
}

Related Tutorials