CS 151 Lecture 9

Cover page image

Cay S. Horstmann

Lecture 9 Clicker Question 1

Consider this method:

public static String largest(String[] values, Comparator<String> comp)
{
   String result = null;
   for (int i = 0; i < values.length; i++)
      if (i == 0 || comp.compare(result, values[i]) < 0)
         result = values[i];
   return result;
}

What is the result of this call?

String[] words = { "Mary", "had", "a", "little", "zebra" };
String largestWord = largest(words, (s, t) -> Math.max(s.length(), t.length()));
  1. "Mary"
  2. "little"
  3. "zebra"
  4. I have no idea.

Lecture 9 Clicker Question 2

Consider this method:

public static String largest(String[] values, Comparator<String> comp)
{
   String result = values[0];
   for (int i = 1; i < values.length - 1; i++)
      if (comp.compare(result, values[i]) < 0)
         result = values[i];
   return result;
}

What is the result of

String result = largest(new String[] { "Mary" }, null);
  1. A compiler error
  2. A NullPointerException
  3. An ArrayIndexOutOfBoundsException
  4. "Mary"

Lab

Lambda Expressions

  1. Complete this program to compute the average length of the words that are entered in the input line. Use a lambda expression.
  2. The Collection<T> interface has a method removeIf that accepts a Predicate<T>, a functional interface for a function T → boolean. All elements for which the function is true are removed.
    Complete this program to remove all elements with length < 20 from a list of words.

UI Actions

  1. Copy the ~/oodp3code/ch04/action1/ActionTester.java file into your lab9 directory.
  2. Change the program so that one must click the buttons in the correct order (Hello, Goodbye, Hello, ...) Hint: JButton.setEnabled.
  3. Change the program so that the message is changed to Hello 1, Goodbye 1, Hello 2, and so on, incrementing with each button click.

Discussion