Java Reference
In-Depth Information
String>(100) of explicitly calling a constructor for HashMap. Even arrays are objects. So what's
the problem?
To help answer this, we'll note that the whole point of a programming language is to manipulate
values, which, following historical programming-language tradition, are therefore called
first-class values (or citizens, in the terminology borrowed from the 1960s civil rights movement
in the United States). Other structures in our programming languages, which perhaps help us
express the structure of values but which can't be passed around during program execution, are
second-class citizens. Values as listed previously are first-class Java citizens, but various other
Java concepts, such as methods and classes, exemplify second-class citizens. Methods are fine
when used to define classes, which in turn may be instantiated to produce values, but neither
are values themselves. So does this matter? Yes, it turns out that being able to pass methods
around at run-time, and hence making them first-class citizens, is very useful in programming,
and so the Java 8 designers added this ability to Java. Incidentally, you might wonder whether
making other second-class citizens such as classes into first-class-citizen values might also be a
good idea. Various languages such as Smalltalk and JavaScript have explored this route.
1.2.1. Methods and lambdas as first-class citizens
Experiments in other languages such as Scala and Groovy have determined that allowing
concepts like methods to be used as first-class values made programming easier by adding to the
toolset available to programmers. And once programmers become familiar with a powerful
feature, they become reluctant to use languages without it! So the designers of Java 8 decided to
allow methods to be values—to make it easier for you to program. Moreover, the Java 8 feature
of methods as values forms the basis of various other Java 8 features (such as Streams).
The first new Java 8 feature we introduce is that of method references . Suppose you want to
filter all the hidden files in a directory. You need to start writing a method that given a File will
tell you whether it's hidden or not. Thankfully there's such a method inside the File class called
isHidden. It can be viewed as a function that takes a File and returns a boolean. But to use it for
filtering you need to wrap it into a FileFilter object that you then pass to the File.listFiles
method, as follows:
 
Search WWH ::




Custom Search