CS 151

Cover page image

Cay S. Horstmann

Day 7 Clicker Question 1

Which of the following statements are true?

  1. The Icon.paintIcon method is abstract.
  2. The Icon interface is a functional interface.
  3. The IconTester class is coupled with the MarsIcon class.
  4. The JOptionPane class is coupled with the MarsIcon class.

Day 7 Clicker Question 2

What does this lambda expression do?

s -> s.equals(s.toUpperCase())
  1. It turns a string into uppercase.
  2. It tests whether a string is all uppercase.
  3. It tests whether two strings are the same when turned into uppercase.
  4. It always returns false.

Day 7 Clicker Question 3

Consider this method:

public static <T> T largest(T[] values, Comparator<T> comp)
{
   T 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. There is a compile- or runtime error.

Mystified By Lambdas?

If you are totally mystified by lambdas, do this exercise. If you understand the basic idea, skip this and move on to the next slide.

Lambda Practice

Sequence Diagram Practice 1

Consider this call:

JOptionPane.showMessageDialog(. . ., new MarsIcon(50));

Draw a sequence diagram.

Sequence Diagram Practice 2

Consider this method:

public static Comparable largest(Comparable[] values)
{
   Comparable result = null;
   for (int i = 0; i < values.length - 1; i++)
      if (i == 0 || result.compareTo(values[i]) < 0)
         result = values[i];
   return result;
}

and this call:

largest(countries);

where countries is defined as

Country[] countries = new Country[] {
   new Country("Uruguay", 176220),
   new Country("Thailand", 514000),
   new Country("Belgium", 30510) };

Sequence Diagram Practice 3

Repeat with this method

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

and this call:

largest(countries, new CountryComparatorByName());

Discussion

discussion