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.NoSuchElementException;

public class Main {
    /**
     * Returns the single element contained in a collection or a null
     * if the collection is null or empty.
     * 
     * @param c the collection containing a single element
     * @return Object the single element contained in the collection
     * @throws NoSuchElementException If the collection contains more than one element.
     */
    public static Object getUniqueElement(Collection c) throws NoSuchElementException {
        // Return null if list is null or empty
        if (c == null || c.isEmpty())
            return null;

        // Throw an exception if collection has more than one element
        if (c.size() > 1) {
            NoSuchElementException exc = new NoSuchElementException(
                    "CollectionHelper.getUniqueElement() called with a collection containing "
                            + "more than one element.");
            throw exc;
        }

        return c.iterator().next();
    }
}