Java OCA OCP Practice Question 3173

Question

What will the program print when compiled and run?

import java.util.Collection;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    NavigableMap<String, Integer> grades = new TreeMap<String, Integer>();
    grades.put("A",  5); grades.put("B", 10); grades.put("C", 15);
    grades.put("D", 20); grades.put("E", 25);

    System.out.printf("1:%d, ", grades.get(grades.firstKey()));
    System.out.printf("2:%d, ", sumValues(grades.headMap("D")));
    System.out.printf("3:%d, ", sumValues(grades.subMap("B", false, "D", true)));
    grades.subMap(grades.firstKey(), false, grades.lastKey(), false).clear();
    System.out.printf("4:%d%n", sumValues(grades));
  }/*from  w  w  w.j a v a2s .c o m*/

  public static <K, M extends Map<K, Integer>> int sumValues(M freqMap) {
    Collection<Integer> values = freqMap.values();
    int sumValues= 0;
    for (int value : values)
      sumValues += value;
    return sumValues;
  }
}

Select the one correct answer.

  • (a) 1:5, 2:50, 3:35, 4:30
  • (b) 1:5, 2:30, 3:35, 4:30
  • (c) 1:5, 2:30, 3:25, 4:30
  • (d) 1:5, 2:30, 3:35, 4:75


(b)

Note

A map view method creates half-open intervals (i.e., the upper bound is not included), unless the inclusion of the bounds is explicitly specified.

Clearing a map view clears the affected entries from the underlying map.

The argument to the sumValues() method can be any subtype of Map, where the type of the value is Integer.




PreviousNext

Related