2

I want to pass an array as argument to a function without first element.

I came up with this solution, but I'm wondering if there are better ways to it.

List<Integer> numbers = new ArrayList<>();
//... in the meantime numbers is an array that contain 1000 elements;
numbers.remove(0);
myFunction(numbers)
  • 2
    The question and code seem to imply different things. An _array_ vs. a `List`. – BeUndead Sep 13 '19 at 13:38
  • You are not passing an array, but an `ArrayList`. There are different ways, `subList()` as already mentioned or even a loop in `myFunction` that does not consider index 0, but loops from 1 to `numbers.size() - 1`. A matter of taste and requirements. – deHaar Sep 13 '19 at 13:40

1 Answers1

3

You can use subList(firstElement, lastElement); method.

Here please check javadoc.

tostao
  • 2,803
  • 4
  • 38
  • 61
  • 1
    Minor note: maybe name it `from, to` instead of `firstElement, lastElement`, since the `lastElement` is excluded (the index-range is `[from, to)`). Also, since he mentions array in the title and description (contradicting his code..), he could use [`java.util.Arrays.copyOfRange(array, from, to);`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Arrays.html#copyOfRange(int%5B%5D,int,int)) if we're talking about `int[]` here instead. Both can be used similarly though: create a copy in the (0-based) index-range `[1, length)`. – Kevin Cruijssen Sep 13 '19 at 13:55