Amen Amen - 3 months ago 27
Java Question

Accessing sub-array and counting an element in arrays in Java

I have 2 questions about arrays in

and any help would be appreciated.

  1. Is there a way to access a sub-array (something like this on
    python: array[1:5]

  2. I want to know does
    has a function that counts a specific element in an
    or not.

I don't want to use for loops.

Answer Source

For your first question, you can use copyOfRange static method of Arrays class.

Example use:

int[] array = new int[]{1, 2, 3, 4, 5};
int[] subArray = Arrays.copyOfRange(array, 1, 3);

//subArray = [2, 3]

And for your second question, that method has to traverse whole array and that cannot be done without a loop.