Solution for the ArrayList exercise: finding the most frequent element in an array

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.


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, -8, 4, 1, 5, 2, 3, -1000000000, 6, 6, -8, 6,
				4, 1, 2, 6, 2, 3, 1, 2, 1, 5, 5, 20000000, 1, 1, 5, -8, 4 };

		ArrayList<Integer> count = new ArrayList<Integer>();
		ArrayList<Integer> seen = new ArrayList<Integer>();
		int highestYet = 0;

		for (int i = 0; i < elements.length; i++) {
			if (!seen.contains(elements[i])) {
				seen.add(elements[i]);
				count.add(1);
			} else {
				int index = 0;

				index = seen.indexOf(elements[i]);
				count.set(index, count.get(index) + 1);
				if (count.get(index) >= count.get(highestYet)) {
					highestYet = index;
				}
			}
		}

		// Your code goes

		// fill in the appropriate results:
		System.out.println("The most frequent element " + seen.get(highestYet)
				+ " occurs " + count.get(highestYet) + " times");
	}
}


CSci 2101 course web site.