Java Collection Create toCollection(Class cls, T[] array)

Here you can find the source of toCollection(Class cls, T[] array)

Description

to Collection

License

Open Source License

Declaration

public static <T, C extends Collection<T>> Collection<T> toCollection(Class<C> cls, T[] array) 

Method Source Code

//package com.java2s;

import java.util.Collection;

public class Main {
    public static <T, C extends Collection<T>> Collection<T> toCollection(Class<C> cls, T[] array) {
        try {/*from w ww .ja va2 s.c o m*/
            Collection<T> collection = cls.newInstance();
            for (T t : array) {
                collection.add(t);
            }
            return collection;
        } catch (RuntimeException re) {
            throw re;
        } catch (Throwable t) {
            throw new IllegalArgumentException(t);
        }
    }

    public static <T> T newInstance(String cls, Class<T> interfaceType) {
        Class<?> clazz;
        try {
            clazz = Class.forName(cls);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("class not found: " + cls, e);
        }
        Object obj;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("cannot instantiate class: " + cls, e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("cannot access no-args constructor of class: " + cls, e);
        }
        T t;
        try {
            t = interfaceType.cast(obj);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "cannot cast new instance of " + cls + " to interface type " + interfaceType.getName());
        }

        return t;
    }

    private static int cast(byte b) {
        if (b >= 0) {
            return b;
        }
        return 256 + b;
    }
}

Related

  1. stringToCollection(String string)
  2. stringToCollection(String string)
  3. stringToCollection(String string, String delim)
  4. toCollection(C c, E... elements)
  5. toCollection(Class cls, Iterable iterable)
  6. toCollection(final char[] charArray)
  7. toCollection(final Iterable iterable)
  8. toCollection(final T[] elements)
  9. toCollection(Iterable iterable)