Advanced Topics MCQ

Code Tracing: Sets, Maps, and Hash Tables

Practice mode shows one question at a time and lets students check each answer before moving on.

All AT CS Tests

For practice use only.

Code Tracing: Sets, Maps, and Hash Tables

Code Tracing: Sets, Maps, and Hash Tables with immediate answer checks and explanations for Advanced Topics in Computer Science.

Question 1 of 25

Answered 0 of 25

Choose one answer.

Trace the frequency map and score. What is printed?

import java.util.HashMap;
import java.util.Map;

public class FrequencyTrace
{
    public static void main(String[] args)
    {
        int[] data = {2, 5, 2, 7, 5, 2, 9};
        Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
        int score = 0;
        for (int value : data)
        {
            int next = freq.getOrDefault(value, 0) + 1;
            freq.put(value, next);
            if (next == 2) score += value;
            else if (next > 2) score -= next;
        }
        System.out.println(score);
    }
}