ArrayList exercise: finding the most frequent element in an array

This is work in progress on the exercise, by Spring 2016 Data Structures class.

Write a program that finds the most frequently occurring element in an array of integers. Use ArrayLists to count the number of occurrences of each element. At the end print the element and its number of occurrences. If there is more than one such element, any one of them may be printed.
When the program is done, we will see what needs to be changed to make it work on an array of Strings.
The starting code is below.
Hint: you need to set up two array lists, one to store elements that you have seen, and the other one to store how many times you have seen each element. As you move through the array in a loop, update the array lists appropriately. Write methods as you find helpful.

import java.util.ArrayList;

public class MostFrequentElement {

       Given an array of ints, the program finds and prints the most 
       frequently occurring element and its number of occurrences. 
       If there is more than one such element, any one of them may be 
       Assume that the given array contains at least one element.
    public static void main(String [] args) {
	// in this example 1 is the most frequent element, it appears 7 times:
	int [] elements = {1, 3, 4, 1, 5, 2, 3, 6, 6, 6, 4, 1, 2, 6, 2, 3,
			   1, 2, 1, 5, 5, 1, 1, 5, 4};

	// Your code goes 
	ArrayList<Integer> alreadySeen = new ArrayList<Integer>();
	ArrayList<Integer> counter = new ArrayList<Integer>();
	for (int n : elements) {
		int index = alreadySeen.indexOf(n);
		if (index != -1) {
			counter.set(index, counter.get(index) + 1);
		} else {

        // fill in the appropriate results:
	System.out.println("The most frequent element " +  " occurs " +  " times");
    public static boolean seenBefore(int n, ArrayList<Integer> bob) {
    	    for(int x: bob) {
		    if(n == x) {
		    	    return true;
	    return false;
    public static int indexOfN(int n, ArrayList<Integer> narration) {
    	    int x = 0;
    	    for(int i: narration) {
    	    	    if(i == n) {
    	    	    	    return x;
    	    return -1;

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.