Quiz 03 sample questions and answers

Suppose you have a class with an instance variable evensSet of type Set<Integer>. The value of evensSet is non-null. Write an instance method with signature void addEvens(int low, int high) that adds to evenSet the even integers between low and high, inclusive.

void addEvens(int low, int high) {
  for (int i = low; i <= high; i++) {
    if (i % 2 == 0) evenSet.add(i);
  }
}

Write a static method with signature void updateCount(Map<Variety, Integer> varietyCount, Variety banana, int count). updateCount should increase the Integer associated in the map with the given banana variety by the amount count (or set it equal to count if banana is not yet in the map). Assume varietyCount and banana are non-null, and that Variety has meaningful equals and hashCode methods.

void updateCount(Map<Variety, Integer> varietyCount, Variety banana, int count) {
  varietyCount.put(banana, varietyCount.getOrDefault(banana, 0) + count);
}

State the approximate worst-case running time for each of the following:

  • ArrayList.add: linear in size of the list
  • HashSet.size: constant time