sort And Clone String array - Java java.lang

Java examples for java.lang:String Array

Description

sort And Clone String array

Demo Code

/*//from ww  w .  j a va  2s .  c o m
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */
//package com.java2s;
import java.lang.reflect.Array;
import java.util.Arrays;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(java.util.Arrays.toString(sortAndClone(array)));
    }

    public static String[] sortAndClone(String[] array) {
        if (array == null) {
            return array;
        }

        String[] clonedArray = arrayClone(array);
        Arrays.sort(clonedArray);

        return clonedArray;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] arrayClone(T[] array) {
        if (array == null) {
            return array;
        }
        if (array.length == 0) {
            return (T[]) Array.newInstance(array.getClass()
                    .getComponentType(), 0);
        }

        T[] clonedArray = (T[]) Array.newInstance(array[0].getClass(),
                array.length);
        System.arraycopy(array, 0, clonedArray, 0, array.length);

        return clonedArray;
    }
}

Related Tutorials