-1

Need to make this generic:

public static String[] tail(String[] array) {
    String[] result = new String[array.length - 1];
    System.arraycopy(array, 1, result, 0, result.length);
    return result;
}

Such that:

assertArrayEquals(new Integer[]{2, 3}, tail(new Integer[]{1, 2, 3}));

assertArrayEquals(new String[]{"B", "C"}, tail(new String[]{"A", "B", "C"}));

assertArrayEquals(new String[]{"C"}, tail(tail(new String[]{"A", "B", "C"})));

assertArrayEquals(new String[]{}, tail(new String[]{"A"}).length);

And such that tail(new String[0]) is illegal.

I can't find anything on SO for tail on array, just tail of Lists etc, but I want to use in the context of variable length argument lists without converting the array to a List.

Example usage of tail with variable length argument:

public static File file(String root, String... parts) {
    return file(new File(root), parts);
}

public static File file(File root, String... parts) {
    if (parts.length == 0)
        return root;
    return file(new File(root, parts[0]), tail(parts));
}
weston
  • 54,145
  • 21
  • 145
  • 203
  • Downvote is for not clear, not useful, or not researched. Please elaborate to which you think this falls under. – weston Oct 22 '15 at 12:43

1 Answers1

6
public static <T> T[] tail(T[] array) {
    if (array.length == 0)
        throw new IllegalArgumentException("Array cannot be empty");

    return java.util.Arrays.copyOfRange(array, 1, array.length);
}

Note I recommend overloading for primitive types to avoid boxing.

weston
  • 54,145
  • 21
  • 145
  • 203
  • what if you you pass null? – Tahar Bakir Oct 22 '15 at 11:56
  • 1
    @TaharBakir You get a NPE from `array.length`, which I'm OK with. – weston Oct 22 '15 at 11:58
  • if (array==null || array.length == 0) You don't get the npe and you throw that runtimeEx but if it's ok, no arguing here :) – Tahar Bakir Oct 22 '15 at 12:08
  • @TaharBakir I see, yes you could do that, but I would use a different message if I was going to do that because `null` isn't the same as an empty array. – weston Oct 22 '15 at 12:40
  • @TaharBakir Been looking in to this, and if I was to throw a custom exception on `null`, that exception should be `NullPointerException` over any other exception type anyway. So no point throwing it myself. See http://stackoverflow.com/a/3323006/360211 and the first comment. – weston Oct 23 '15 at 08:09