Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import java.util.HashSet;
import java.util.List;

public class Main {
    /**
     * Returns a collection with fast contains() implementation. The collection
     * is intended to be reusable, a single use will not be efficient. Most
     * efficient with primitive objects (String, Integer...)
     */
    @SuppressWarnings("unchecked")
    public static <T> Collection<T> fastSearchCollection(T... arr) {
        final int size = arr.length;
        if (size == 0)
            return Collections.EMPTY_LIST;

        if (size == 1)
            Collections.singletonList(arr[0]);

        // optimization for short list, avoid hash
        if (size <= 8) {
            return Arrays.asList(arr);
        }
        // big lists, use hash (constant time)
        return new HashSet<T>(Arrays.asList(arr));
    }

    /**
     * Returns a collection with fast contains() implementation. The collection
     * is intended to be reusable. A single use will not be efficient as it
     * allocates memory for the new collection.
     * 
     * Most efficient with primitive objects (String, Integer...)
     */
    @SuppressWarnings("unchecked")
    public static <T> Collection<T> fastSearchCollection(List<T> list) {
        final int size = list.size();
        if (size == 0)
            return Collections.EMPTY_LIST;

        if (size == 1)
            Collections.singletonList(list.get(0));

        // optimization for short list, avoid hash
        if (size <= 8) {
            if (list instanceof ArrayList)
                // ArrayList similar to Arrays for short lists, save some
                // memory.
                return (ArrayList<T>) list;

            // not ArrayList, play safe with final array type list
            T[] s = (T[]) list.toArray();
            return Arrays.asList(s);
        }
        // big lists, use hash (constant time)
        return new HashSet<T>(list);
    }
}