Java Reference
In-Depth Information
you to sort the apples by color. Sound familiar? Yes, you need a way to represent and use
different sorting behaviors to easily adapt to changing requirements.
In Java 8, a List comes with a sort method (you could also use Collections .sort). The behavior of
sort can be parameterized using a java.util.Comparator object, which has the following interface:
// java.util.Comparator
public interface Comparator<T> {
public int compare(T o1, T o2);
}
You can therefore create different behaviors for the sort method by creating an ad hoc
implementation of Comparator. For example, you can use it to sort the inventory by increasing
weight using an anonymous class:
inventory.sort(new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
});
If the farmer changes his mind about how to sort apples, you can create an ad hoc Comparator
to match the new requirement and pass it to the sort method! The internal details of how to sort
are abstracted away. With a lambda expression it would look like this:
inventory.sort(
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));
Again, don't worry about this new syntax for now; the next chapter covers in detail how to write
and use lambda expressions.
2.4.2. Executing a block of code with Runnable
Threads are like a lightweight process: they execute a block of code on their own. But how can
you tell a thread what block of code to run? Several threads may run different code. What you
need is a way to represent a piece of code to be executed later. In Java, you can use the Runnable
interface to represent a block of code to be executed; note that the code will return no result
(that is, void):
// java.lang.Runnable
 
Search WWH ::




Custom Search