Tracing a generic method and counting compiled copies

Consider this Java generic method and the calls that follow it.


Java
public static < T > int countMatches(T[] items, T target) {
    int count = 0;
    for (int i = 0; i < items.length; i++)
        if (items[i].equals(target)) count++;
    return count;
}

Integer[] readings = {4, 9, 4, 4, 1, 9};
String[] colours = {"red", "blue", "red", "green"};
int x = countMatches(readings, 4);
int y = countMatches(colours, "red");


Find the value stored in x, the value stored in y, the number of compiled method bodies for countMatches in the Java class file, and the number of instantiations a C++ compiler would generate if the method were rewritten as a function template and called once with an int array and once with a std::string array. Give each answer as a whole number.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Generics Questions: