Java Reference
In-Depth Information
public String toString()
return birds.toString();
class EmptyListDemo
public static void main(String[] args)
Birds birds = new Birds();
birds = new Birds("Swallow", "Robin", "Bluejay",
Listing 5-26 declares a Birds class that stores the names of various birds in a list.
This class provides two constructors, a noargument constructor and a constructor that
takes a variable number of String arguments identifying various birds.
Thenoargumentconstructorinvokes emptyList() toinitializeitsprivate birds
fieldtoanempty List of String emptyList() isagenericmethodandthecom-
piler infers its return type from its context.
If you're wondering about the need for emptyList() , look at the toString()
method.Noticethatthismethodevaluates birds.toString() .Ifwedidnotassign
areferencetoanempty List<String> to birds , birds wouldcontain null (the
default value for this instance field when the object is created), and a NullPoint-
erException instance would be thrown when attempting to evaluate
birds.toString() .
Whenyourunthisapplication( java EmptyListDemo ),itgeneratesthefollowing
[Swallow, Robin, Bluejay, Oriole]
Search WWH ::

Custom Search