build Unmodifiable Set - Java java.util

Java examples for java.util:Set Creation

Description

build Unmodifiable Set

Demo Code


//package com.book2s;
import static java.util.Collections.*;
import static java.lang.String.*;
import java.util.*;

public class Main {
    public static <T> Set<T> buildUnmodifiableSet(T... theElements) {

        if (theElements == null) {

            return emptySet();

        }//w  w w  .  j av a2 s.c om

        Set<T> aSet = new HashSet<T>(theElements.length);

        for (T anElement : theElements) {

            boolean aResult = aSet.add(anElement);

            if (aResult != true) {

                throw new IllegalStateException(
                        format("Attempt to add a duplicate element, %1$s, to set.",
                                anElement));

            }

        }

        return unmodifiableSet(aSet);

    }
}

Related Tutorials