Example usage for java.util Collection getClass

List of usage examples for java.util Collection getClass

Introduction

In this page you can find the example usage for java.util Collection getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:Main.java

@SuppressWarnings("unchecked")
public static <E> Collection<E> union(Collection<E> collectionA, Collection<E> collectionB) {
    Collection<E> collectionC = null;
    try {//from   w  ww .  j  a v a2s. co  m
        collectionC = collectionA.getClass().newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        return collectionC;
    }
    Iterator<E> aIterator = collectionA.iterator();
    Iterator<E> bIterator = collectionB.iterator();
    while (aIterator.hasNext() || bIterator.hasNext()) {
        if (aIterator.hasNext()) {
            E ae = aIterator.next();
            if (!collectionC.contains(ae)) {
                collectionC.add(ae);
            }
        }
        if (bIterator.hasNext()) {
            E be = bIterator.next();
            if (!collectionA.contains(be) && !collectionC.contains(be)) {
                collectionC.add(be);
            }
        }
    }
    return collectionC;
}

From source file:Main.java

public static <T> T getFirstElement(Collection<T> collection, T defaultValue) {
    T elem = defaultValue;//ww w  .j a va2  s. co  m
    if (collection != null && !collection.isEmpty()) {
        if (List.class.isAssignableFrom(collection.getClass())) {
            elem = ((List<T>) collection).get(0);
        } else {
            for (T item : collection) {
                elem = item;
                break;
            }
        }
    }
    return elem;
}

From source file:Main.java

/**
 * Ensures the given is sortable, i.e. is a List and implements {@link RandomAccess}. If not
 * it will be copied to a collection that is sortable.
 * @param collection/*from  www.ja v  a 2 s .c  om*/
 * @return
 */
public static <T> List<T> ensureSortable(Collection<T> collection) {

    if (collection == null) {
        return null;
    }

    if (collection instanceof RandomAccess && collection instanceof List
            && !collection.getClass().getName().toLowerCase().contains("unmodifiable")) {
        return (List<T>) collection;
    }

    return new ArrayList<T>(collection);
}

From source file:Main.java

public static <T> List<Collection<T>> splitCollection(Collection<T> col, int numLists)
        throws InstantiationException, IllegalAccessException {
    List<Collection<T>> lstReturn = new ArrayList<Collection<T>>();
    Iterator<T> iter = col.iterator();

    for (int c = 0; c < numLists; c++) {
        Collection<T> temp = col.getClass().newInstance();
        lstReturn.add(temp);/*w  ww.  ja v a 2 s. co m*/
    }

    while (iter.hasNext()) {
        for (int collectionIndex = 0; collectionIndex < numLists; collectionIndex++) {
            if (iter.hasNext()) {
                Collection<T> current = lstReturn.get(collectionIndex);
                T value = iter.next();
                current.add(value);
            }
        }
    }

    return lstReturn;
}

From source file:org.broadleafcommerce.common.util.BLCCollectionUtils.java

/**
 * Create a collection proxy that will perform some piece of work whenever modification methods are called on the
 * proxy. This includes the add, allAll, remove, removeAll, clear methods. Additionally, calling remove on an iterator
 * created from this collection is also covered.
 *
 * @param work the work to perform on collection modification
 * @param original the original collection to make change aware
 * @param <T> the collection type (e.g. List, Set, etc...)
 * @return the proxied collection/*from ww  w .  ja va2 s. c om*/
 */
public static <T extends Collection> T createChangeAwareCollection(final WorkOnChange work,
        final Collection original) {
    T proxy = (T) Proxy.newProxyInstance(BLCCollectionUtils.class.getClassLoader(),
            ClassUtils.getAllInterfacesForClass(original.getClass()), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().startsWith("add") || method.getName().startsWith("remove")
                            || method.getName().startsWith("clear")) {
                        work.doWork(original);
                    }
                    if (method.getName().equals("iterator")) {
                        final Iterator itr = (Iterator) method.invoke(original, args);
                        Iterator proxyItr = (Iterator) Proxy.newProxyInstance(getClass().getClassLoader(),
                                ClassUtils.getAllInterfacesForClass(itr.getClass()), new InvocationHandler() {
                                    @Override
                                    public Object invoke(Object proxy, Method method, Object[] args)
                                            throws Throwable {
                                        if (method.getName().equals("remove")) {
                                            work.doWork(original);
                                        }
                                        return method.invoke(itr, args);
                                    }
                                });
                        return proxyItr;
                    }
                    return method.invoke(original, args);
                }
            });
    return proxy;
}

From source file:com.swtxml.util.lang.CollectionUtils.java

@SuppressWarnings("unchecked")
private static Collection createCollection(Collection original) {
    if (original instanceof Set) {
        return new HashSet();
    }/*from  ww w. j av a  2s .  c o m*/
    if (original instanceof Collection) {
        return new ArrayList();
    }
    throw new ReflectorException("Unknown collection type: " + original.getClass());
}

From source file:com.yahoo.bard.webservice.util.Utils.java

/**
 * A recursive call to make a collection and all it's values immutable.
 *
 * @param <T>  The type of the collection
 * @param mutableCollection  The original, potentially mutable, collection
 *
 * @return Am immutable copy whose values are also immutable.
 *//*from  w ww. j  a va  2 s  .  c  o m*/
public static <T> Collection<T> makeImmutable(Collection<T> mutableCollection) {
    Collection<T> newCollection;
    try {
        @SuppressWarnings("unchecked")
        Class<Collection<T>> cls = (Class<Collection<T>>) mutableCollection.getClass();
        newCollection = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
    for (T element : mutableCollection) {
        newCollection.add(Utils.makeImmutable(element));
    }
    return Collections.unmodifiableCollection(newCollection);
}

From source file:org.geoserver.catalog.impl.ModificationProxyCloner.java

/**
 * Shallow or deep copies the provided collection
 * /*w  w  w.  ja  v  a 2 s  .c o m*/
 * @param source
 * @param deepCopy If true, a deep copy will be done, otherwise the cloned collection will
 *        contain the exact same objects as the source
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
public static <T> Collection<T> cloneCollection(Collection<T> source, boolean deepCopy)
        throws InstantiationException, IllegalAccessException {
    if (source == null) {
        // nothing to copy
        return null;
    }
    Collection<T> copy = source.getClass().newInstance();
    if (deepCopy) {
        for (T object : source) {
            T objectCopy = clone(object);
            copy.add(objectCopy);
        }
    } else {
        copy.addAll(source);
    }

    return copy;
}

From source file:Main.java

/**
 * Generate a usually multiline String reporting a collection's elements. If the collection is a Map.entrySet(), actually if elements
 * are instances of Map.Entry then their key is reported instead of the element's index.
 *
 * @param theLabel A label to display first, as is without change. If null, "" is used.
 * @param coll A collection whose elements will be listed (if not too large)
 * @param maxNumberReported The maximum number of elements to report in case of large collections, or 0 to report all whatever the size.
 * @return A usually multiline String describing the collection. This can be logged, or output to System.out, for instance. If the
 *         collection is empty, one line is output. If the collection is large, only the first and last elements are output, while "..."
 *         is shown in the middle./* w  w w.  j a  v a  2 s  . com*/
 */
public static String format(String theLabel, Collection<?> coll, int maxNumberReported) {
    String label = theLabel;
    if (coll == null) {
        if (label == null) {
            label = "";
        }
        return label + " null Collection";
    }
    return format(label, coll, maxNumberReported, coll.getClass().getSimpleName());
}

From source file:org.jfree.data.KeyToGroupMap.java

/**
 * Returns a clone of the list.//  w  w w  .j a v  a  2s. c  om
 *
 * @param list  the list.
 *
 * @return A clone of the list.
 *
 * @throws CloneNotSupportedException if the list could not be cloned.
 */
private static Collection clone(Collection list) throws CloneNotSupportedException {
    Collection result = null;
    if (list != null) {
        try {
            List clone = (List) list.getClass().newInstance();
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                clone.add(KeyToGroupMap.clone(iterator.next()));
            }
            result = clone;
        } catch (Exception e) {
            throw new CloneNotSupportedException("Exception.");
        }
    }
    return result;
}