Joni
0
Q:

how to count the number of occurrences of a character in an arraylist recursively

/**
     * Returns the number of occurrences of the character in the array list.
     * @param list the array list
     * @param ch the character
     * @return the number of occurrences of the character in the array list
     */
    public static int howMany(ArrayList<Character> list, char ch) {
        return howMany(list, ch, 0);
    }

    /**
     * Takes a character arraylist, character and an idex as arguments.
     * @param list the arraylist
     * @param ch the character
     * @param index the index
     * @return the number of occurences of the character in the list
     */
    private static int howMany(ArrayList<Character> list, char ch, int index) {
        if (list == null || list.isEmpty() || index < 0) {
            return -1;
        }
        
        if (index > list.size() - 1) {
            return 0;
        } else if (list.get(index).equals(ch)) {
            return 1 + howMany(list, ch, index + 1);
        }
        
        return howMany(list, ch, index + 1);
    }
0

New to Communities?

Join the community