Java Reference
In-Depth Information
@Override
public String toString()
{
return birds.toString();
}
}
class EmptyListDemo
{
public static void main(String[] args)
{
Birds birds = new Birds();
System.out.println(birds);
birds = new Birds("Swallow", "Robin", "Bluejay",
"Oriole");
System.out.println(birds);
}
}
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
output:
[]
[Swallow, Robin, Bluejay, Oriole]