Java List Random Item asRandomAccessList(Collection list)

Here you can find the source of asRandomAccessList(Collection list)

Description

Returns a list implementation that allows for efficient random access.

License

Apache License

Declaration

public static <T> List<T> asRandomAccessList(Collection<T> list) 

Method Source Code

//package com.java2s;
/*-------------------------------------------------------------------------+
|                                                                          |
| Copyright 2005-2011 The ConQAT Project                                   |
|                                                                          |
| Licensed under the Apache License, Version 2.0 (the "License");          |
| you may not use this file except in compliance with the License.         |
| You may obtain a copy of the License at                                  |
|                                                                          |
|    http://www.apache.org/licenses/LICENSE-2.0                            |
|                                                                          |
| Unless required by applicable law or agreed to in writing, software      |
| distributed under the License is distributed on an "AS IS" BASIS,        |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and      |
| limitations under the License.                                           |
+-------------------------------------------------------------------------*/

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

import java.util.RandomAccess;

public class Main {
    /**//from   ww w .j  av  a  2s .  c  om
     * Returns a list implementation that allows for efficient random access.
     * 
     * If the passed collection already supports random access, it gets returned
     * directly. Otherwise a list that supports random access is returned with
     * the same content as the passed list.
     */
    public static <T> List<T> asRandomAccessList(Collection<T> list) {
        // It is not guaranteed that implementations of RandomAccess also
        // implement List. Hence, we check for both.
        if (list instanceof List<?> && list instanceof RandomAccess) {
            return (List<T>) list;
        }

        return new ArrayList<T>(list);
    }
}

Related

  1. choice(List list)
  2. choice(T... list)
  3. choose(Random random, List list)
  4. chooseRandom(List list)