Accessing sub array and counting an element in arrays in Java

I have 2 questions about arrays in java 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 java has a function that counts a specific element in an array or not.

I don't want to use for loops.

Jon Skeet
people
quotationmark

For accessing part of an array, you could use Arrays.asList to obtain a List<E>, and then use the subList method to obtain a slice:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        String[] array = { "zero", "one", "two", "three", "four", "five", "six" };
        List<String> list = Arrays.asList(array);
        List<String> sublist = list.subList(1, 5);
        for (String item : sublist) {
            System.out.println(item);
        }
    }
}

Output:

one
two
three
four

For your second question: even if such a method existed, it would have to loop. I'm not aware of any such method in the standard libraries, so I suggest you write your own using a loop.

people

See more on this question at Stackoverflow