11.8. Using Caller-Supplied Behavior

In the previous section, we used a predicate to decide whether an array element passes a test. The caller supplied an object that implements Predicate<T>, and our method called test through that object's reference. Let's apply the same idea to actions, comparisons, and array creation.

The examples on this page are available in cs1302-generic-behavior. They use the standard interfaces from java.util and java.util.function.

11.8.1. Which Method Do We Call?

Start by reading the abstract method's declaration. Substitute the type arguments, then identify the parameters and result:

Table 11.1 Four Ways to Supply Behavior

Interface type

Abstract method after substitution

What the caller supplies

Consumer<String>

void accept(String item)

An action using a string reference; no result value.

Predicate<String>

boolean test(String item)

A test that produces true or false.

Comparator<String>

int compare(String first, String second)

An ordering between two items.

IntFunction<String[]>

String[] apply(int length)

A function with an int input and an array-reference result.

Notice that IntFunction<String[]> has one parameter, whose type is int. Its type argument describes the result type. It does not change the parameter to String[] or Integer.

Creating the object is different from invoking its behavior. Evaluating a lambda expression supplies a reference to an object implementing the functional interface. The lambda body executes when the corresponding interface method is called. Assigning that reference to a variable or passing it to another method does not itself execute the body.

Consider this helper. Read the test and action calls in the order they would execute:

public static <T> void forEachMatch(T[] items, Predicate<T> test, Consumer<T> action) {
    for (T item : items) {
        if (test.test(item)) {
            action.accept(item);
        } // if
    } // for
} // forEachMatch

test.test(item) supplies the boolean value used by the if statement. For a matching item, action.accept(item) performs the supplied action. The action returns without a value when it completes normally. A return inside a lambda body completes that invocation; it does not return from forEachMatch. An exception thrown by a callback propagates through the helper unless the helper catches it.

11.8.2. Supplying an Ordering

An item's natural ordering comes from its Comparable implementation. A comparator supplies an ordering independently of the item class. This lets us compare objects whose class has no natural ordering, or choose a different ordering for a particular use.

Here is a helper that stores the caller's comparator reference:

import java.util.Comparator;
import java.util.Objects;

/** Selects between two items using a supplied ordering.
 * @param <T> the item type
 */
public final class Chooser<T> {
    /** The caller's ordering object. */
    private final Comparator<T> ordering;

    /**
     * Stores the supplied comparator reference.
     * @param ordering the comparator
     * @throws NullPointerException if ordering is null
     */
    public Chooser(Comparator<T> ordering) {
        this.ordering = Objects.requireNonNull(ordering);
    } // Chooser

    /**
     * Chooses the greater item, choosing the first on a tie.
     * @param first the first item, acceptable to the comparator
     * @param second the second item, acceptable to the comparator
     * @return the selected argument's reference value, possibly null if permitted by the comparator
     */
    public T choose(T first, T second) {
        if (ordering.compare(first, second) >= 0) {
            return first;
        } // if
        return second;
    } // choose
} // Chooser

Chooser<T> does not need a Comparable<T> bound. It compares the arguments by calling ordering.compare(first, second). The constructor stores the supplied reference; it does not copy the comparator object.

The comparison result is a sign, not a count or a distance. Check whether it is negative, zero, or positive; do not assume that a comparator returns with only -1, 0, or 1. A valid comparator must describe a consistent ordering. For example, if it orders the first item above the second and the second above the third, it must order the first above the third.

Consider a comparator that compares strings by length:

Comparator<String> byLength = (String a, String b) -> {
    return Integer.compare(a.length(), b.length());
}; // lambda

A zero result means equal ordering under this policy. It does not require a.equals(b) to be true. For example, "pear" and "plum" have the same length. Chooser explicitly selects its first argument on a tie; that is a decision made by the helper, not by the comparator.

To reverse this ordering, swap the arguments to Integer.compare:

Comparator<String> byLengthReversed = (String a, String b) -> {
    return Integer.compare(b.length(), a.length());
}; // lambda

With this comparator, Chooser selects the shorter string. The caller still needs to interpret the comparison result according to the method's contract. In an urgency queue, a positive comparison means that the first item is more urgent. Existing items with equal urgency retain their arrival order; that rule is part of the queue contract.

Note

Prefer comparison methods over subtracting arbitrary integer values. Subtraction can overflow and produce a result with the wrong sign. For example, Integer.MAX_VALUE - (-1) is negative, although Integer.MAX_VALUE is greater than -1. Integer.compare handles this comparison correctly. Similarly, negating an arbitrary comparator result can overflow; swap its arguments or use its reversed() method.

11.8.3. Supplying an Array Generator

As we saw in the generics chapter, new T[length] cannot create an array inside a generic method. The caller, however, can name a concrete component type:

IntFunction<String[]> generator = (int length) -> {
    return new String[length];
}; // lambda

Now, a generic helper can request the array by invoking the generator:

public static <T> T[] makeArray(int length, IntFunction<T[]> generator) {
    return generator.apply(length);
} // makeArray
String[] result = BehaviorDemo.makeArray(3, generator);

The call to generator.apply(3) executes the lambda body, which creates a String[] of length 3. The helper returns with that array reference. The helper does not create the array by casting an Object[].

For this helper, assume a nonnegative length and a non-null generator that creates an array of the requested length. Each element initially contains null. Assigning item references into those elements is a separate operation. Copying those reference values would not clone the item objects.

In the UrgencyQueue API, toArray accepts an IntFunction<ItemType[]>. The caller supplies the allocation behavior; the queue implementation invokes it and supplies the array's contents according to the API contract. Read the method's requirements for ordering and preservation of the calling queue's state.

11.8.4. Captured Variables and Side Effects

A lambda body can use local variables from its enclosing scope. Those locals must be final or effectively final: they are not reassigned after initialization. Consider the threshold in this example:

int minimum = 4;
Predicate<String> longEnough = (String text) -> {
    return text.length() >= minimum;
}; // lambda

We can call longEnough.test("pear") later. However, adding minimum = 5 after the lambda declaration would make the example fail compilation. minimum would no longer be effectively final.

This rule restricts assignment to the captured local variable. It does not make an object referred to by that variable immutable. For example, a captured array reference can still be used to change an array element. Such code may compile and still violate a method's behavioral contract.

Our forEachMatch helper requires callbacks to leave its input array and items unchanged. Printing a matching string satisfies that requirement. Changing an input element from the predicate does not. The UrgencyQueue API similarly requires non-interfering behavior: callbacks must not modify the calling queue or items held by it. This is an API requirement, not an extra restriction checked by the Java compiler. Side effects such as printing are still possible.

Shorter Forms Using Method References (Optional)

When the intended behavior already has a suitable method or constructor, a method reference can express that behavior more briefly:

IntFunction<String[]> generator = String[]::new;
Consumer<String> print = System.out::println;

The first expression supplies array-creation behavior. Calling generator.apply(3) creates the array; evaluating String[]::new does not immediately create it. The second supplies printing behavior with a parameter compatible with String and no result value. The interface type still determines the required function contract.

Start with the explicitly typed lambdas above if the short forms hide which arguments are passed or which result is supplied.

11.8.5. Test Yourself

Before running BehaviorDemo, predict when it prints callbacks ready and which strings are printed by the consumer. Then compare your prediction with the complete driver:

BehaviorDemo Source
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.function.Predicate;

/** Demonstrates invoking caller-supplied behavior without implementing a queue. */
public final class BehaviorDemo {
    /** Prevents construction of this utility class. */
    private BehaviorDemo() {
    } // BehaviorDemo

    /**
     * Applies an action to each array element that passes a test, in array order.
     * Callbacks must not modify the array or its elements.
     * @param <T> the item type
     * @param items the non-null array
     * @param test the non-null test
     * @param action the non-null action
     */
    public static <T> void forEachMatch(T[] items, Predicate<T> test, Consumer<T> action) {
        for (T item : items) {
            if (test.test(item)) {
                action.accept(item);
            } // if
        } // for
    } // forEachMatch

    /**
     * Requests an array from a caller-supplied generator.
     * @param <T> the component type
     * @param length the nonnegative requested length
     * @param generator the non-null generator that creates an array of that length
     * @return the array reference supplied by the generator
     */
    public static <T> T[] makeArray(int length, IntFunction<T[]> generator) {
        return generator.apply(length);
    } // makeArray

    /**
     * Runs the examples.
     * @param args unused command-line arguments
     */
    public static void main(String[] args) {
        Comparator<String> byLength = (String a, String b) -> {
            return Integer.compare(a.length(), b.length());
        }; // lambda
        Chooser<String> chooser = new Chooser<>(byLength);
        System.out.println(chooser.choose("pear", "fig"));
        System.out.println(chooser.choose("pear", "plum"));

        int minimum = 4;
        Predicate<String> longEnough = (String text) -> {
            return text.length() >= minimum;
        }; // lambda
        Consumer<String> print = (String text) -> {
            System.out.println(text);
        }; // lambda
        System.out.println("callbacks ready");
        forEachMatch(new String[] {"pear", "fig", "plum"}, longEnough, print);

        IntFunction<String[]> generator = (int length) -> {
            return new String[length];
        }; // lambda
        String[] result = makeArray(3, generator);
        System.out.println(result.length);
        System.out.println(result.getClass().getComponentType().getSimpleName());

        IntFunction<String[]> shortGenerator = String[]::new;
        Consumer<String> shortPrint = System.out::println;
        shortPrint.accept("short form: " + makeArray(2, shortGenerator).length);
    } // main
} // BehaviorDemo

Try Questions 12–15 in Additional Practice Exercises. Consult the Java API documentation for Comparator and IntFunction for their full contracts. The UrgencyQueue API specifies which operations invoke user-supplied behavior and the requirements that behavior must meet.