slice array by offset and length - Java Collection Framework

Java examples for Collection Framework:Array Length

Description

slice array by offset and length

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] strings = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        int begin = 2;
        int length = 2;
        System.out.println(java.util.Arrays.toString(slice(strings, begin,
                length)));//from   w w w  . j  a va 2 s .com
    }

    public static String[] slice(String[] strings, int begin, int length) {
        String[] result = new String[length];
        for (int i = 0; i < length; i++) {
            result[i] = strings[begin + i];
        }
        return result;
    }

    public static Object[] slice(Object[] objects, int begin, int length) {
        Object[] result = new Object[length];
        for (int i = 0; i < length; i++) {
            result[i] = objects[begin + i];
        }
        return result;
    }

    public static String toString(Object[] array) {
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i < array.length - 1)
                sb.append(",");
        }
        sb.append("]");
        return sb.toString();
    }
}

Related Tutorials