Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    public static boolean hasInstance(Class clazz, Collection objects) {
        return (getFirstInstance(clazz, objects) != null);
    }

    /**
     * Returns the first object of given type or its subtypes
     * @param clazz The class you want to return the first instance found of.
     * @param objects The collection you'd like to search.
     * @return The first instance of a specific Class found in a Collection.  Returns null if no instance is found.
     */
    public static Object getFirstInstance(Class clazz, Collection objects) {
        if (objects != null && clazz != null) {
            Iterator objectsIterator = objects.iterator();
            while (objectsIterator.hasNext()) {
                Object instance = objectsIterator.next();
                if (clazz.isAssignableFrom(instance.getClass())) {
                    return instance;
                }
            }
        }
        return null;
    }
}