Get a part on an array, sub array - Java Collection Framework

Java examples for Collection Framework:Array Sub Array

Description

Get a part on an array, sub array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object[] data = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        int startIndex = 2;
        int endIndex = 2;
        System.out.println(java.util.Arrays.toString(subArray(data,
                startIndex, endIndex)));
    }//from   w ww. j a v  a  2s.c  o m

    /**
     * Get a part on an array
     * @param data The array to get the sub array from
     * @param startIndex The first index of the subarray
     * @param endIndex The first index not in the subarray (last index +1)
     * @return an array with the elements from data in the fields startIndex to endIndex-1
     */
    public static Object[] subArray(Object[] data, int startIndex,
            int endIndex) {
        Object[] output = new Object[endIndex - startIndex];
        for (int i = startIndex; i < endIndex; i++) {
            output[i - startIndex] = data[i];
        }
        return output;
    }

    /**
     * Get a part on an array
     * @param data The array to get the sub array from
     * @param startIndex The first index of the subarray
     * @param endIndex The first index not in the subarray (last index +1)
     * @return an array with the elements from data in the fields startIndex to endIndex-1
     */
    public static boolean[] subArray(boolean[] data, int startIndex,
            int endIndex) {
        boolean[] output = new boolean[endIndex - startIndex];
        for (int i = startIndex; i < endIndex; i++) {
            output[i - startIndex] = data[i];
        }
        return output;
    }

    /**
     * Get a part on an array
     * @param data The array to get the sub array from
     * @param startIndex The first index of the subarray
     * @param endIndex The first index not in the subarray (last index +1)
     * @return an array with the elements from data in the fields startIndex to endIndex-1
     */
    public static double[] subArray(double[] data, int startIndex,
            int endIndex) {
        double[] output = new double[endIndex - startIndex];
        for (int i = startIndex; i < endIndex; i++) {
            output[i - startIndex] = data[i];
        }
        return output;
    }
}

Related Tutorials