Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.util.Iterator;

public class Main {
    /**
     * Find a value of the given type in the given collection.
     * @param coll the collection to search
     * @param type the type to look for
     * @return a value of the given type found, or <code>null</code> if none
     * @throws IllegalArgumentException if more than one value
     * of the given type found
     */
    public static Object findValueOfType(Collection<?> coll, Class<?> type) throws IllegalArgumentException {
        Object value = null;
        for (Iterator<?> it = coll.iterator(); it.hasNext();) {
            Object obj = it.next();
            if (type.isInstance(obj)) {
                if (value != null) {
                    throw new IllegalArgumentException(
                            "More than one value of type [" + type.getName() + "] found");
                }
                value = obj;
            }
        }
        return value;
    }

    /**
     * Find a value of one of the given types in the given collection:
     * searching the collection for a value of the first type, then
     * searching for a value of the second type, etc.
     * @param coll the collection to search
     * @param types the types to look for, in prioritized order
     * @return a of one of the given types found, or <code>null</code> if none
     * @throws IllegalArgumentException if more than one value
     * of the given type found
     */
    public static Object findValueOfType(Collection coll, Class[] types) throws IllegalArgumentException {
        for (int i = 0; i < types.length; i++) {
            Object value = findValueOfType(coll, types[i]);
            if (value != null) {
                return value;
            }
        }
        return null;
    }
}