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
printed.
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};

ArrayList<Integer> counter = new ArrayList<Integer>();

for (int n : elements) {
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");
System.out.println(counter);
}
/*
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;
}
++x;
}
return -1;
}*/
}

``````

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.