Checks if collections is null in which case an empty Collection is returned, otherwise if collection is not null it is returned. - Android java.util

Android examples for java.util:Collection and Null

Description

Checks if collections is null in which case an empty Collection is returned, otherwise if collection is not null it is returned.

Demo Code

/*/*from w  ww.  jav a  2s . co m*/
 * Copyright 2012 Marco Soeima
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
//package com.book2s;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "book2s.com");
        System.out.println(nonNullCollection(collection));
    }

    /**
     * Checks if <code>collections</code> is <code>null</code> in which case an empty {@link Collection} is returned,
     * otherwise if <code>collection</code> is not <code>null</code> it is returned.
     *
     * @param   <E>
     * @param   collection  The collection to check.
     *
     * @return  An allocated {@link Collection}.
     */
    public static <E> Collection<E> nonNullCollection(
            Collection<E> collection) {
        return (collection == null) ? Collections.<E> emptyList()
                : collection;
    }

    /**
     * Checks if <code>array</code> is <code>null</code> in which case an empty {@link Collection} is returned,
     * otherwise if <code>array</code> is not <code>null</code> it is returned.
     *
     * @param   <E>
     * @param   array  The array to check.
     *
     * @return  An allocated {@link Collection}.
     */
    public static <E> Collection<E> nonNullCollection(E[] array) {
        return (array == null) ? Collections.<E> emptyList() : Arrays
                .asList(array);
    }
}

Related Tutorials