任意の型の配列かコレクションを新しいリストにコピーする

配列で苦労した。java.lang.reflect.Arrayなんて知らないよ。

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.lang.reflect.Array;

public class ToList {


    /**
     * {@code sequence} の各要素を持つ不変リストを戻す。
     *
     * @param sequence 任意の型の配列かコレクション。
     */
    static List< Object > toList( Object sequence ) {
        if ( sequence instanceof Collection ) {
            return Collections.unmodifiableList(
                    new ArrayList< Object >( (Collection< ? >) sequence ) );
        } else if ( sequence.getClass().isArray() ) {
            int size = Array.getLength( sequence );
            List< Object > list = new ArrayList< Object >( size );
            for ( int index = 0 ; index < size ; index++ ) {
                list.add( Array.get( sequence , index ) );
            }
            return Collections.unmodifiableList( list );
        } else {
            throw new IllegalArgumentException(
                    "should be a collection or an array: " + sequence );
        }
    }


    public static void main( String[] args ) {
        // [10, 20, 30]
        System.out.println( toList( new int[] { 10 , 20 , 30 } ) );

        // [10, 20, 30]
        System.out.println( toList( new Long[] { 10L , 20L , 30L } ) );

        // [ping, pong]
        System.out.println( toList( Arrays.asList( "ping" , "pong" ) ) );
    }
}