Java Reference
In-Depth Information
The emptyList() method is implemented as follows: return (List<T>)
EMPTY_LIST; . This statement returns the single List instance assigned to the
EMPTY_LIST class field in the Collections class.
Youmightwanttoworkwith EMPTY_LIST directly,butyou'llrunintoanunchecked
warning message if you do, because EMPTY_LIST is declared to be of the raw type
List ,andmixingrawtypeswithgenerictypesleadstosuchmessages.Althoughyou
could suppress the warning, you're better off using the emptyList() method.
Suppose you add a void setBirds(List<String> birds) method to
Birds , and pass an empty list to this method, as in
birds.setBirds(Collections.emptyList()); .Thecompilerwillrespond
with an error message stating that it requires the argument to be of type
List<String> ,butinsteadtheargumentisoftype List<Object> .Itdoessobe-
causethecompilercannotfigureoutthepropertypefromthiscontext,andsoitchooses
List<Object> .
Thereisawaytosolvethisproblem,whichwillprobablylookverystrange.Specify
birds.setBirds(Collections.<String>emptyList()); , where the
formaltypeparameterlistanditsactualtypeargumentappearafterthememberaccess
operatorandbeforethemethodname.Thecompilerwillnowknowthatthepropertype
argument is String , and that emptyList() is to return List<String> .
Legacy Collections APIs
Java 1.2 introduced the Collections Framework. Prior to the framework's inclusion in
Java, developers had two choices where collections were concerned: create their own
frameworks, or use the Vector , Enumeration , Stack , Dictionary , Hasht-
able , Properties , and BitSet types, which were introduced by Java 1.0.
Vector isaconcreteclassthatdescribesagrowablearray,muchlike ArrayList .
Unlike an ArrayList instance, a Vector instance is synchronized. Vector has
beengenerifiedandalsoretrofittedtosupporttheCollectionsFramework,whichmakes
statements such as List<String> list = new Vector<String>(); legal.
TheCollectionsFrameworkprovides Iterator foriteratingoveracollection'sele-
ments.Incontrast, Vector 's elements() methodreturnsaninstanceofaclassthat
implements the Enumeration interface for enumerating (iterating over and return-
ing)a Vector instance'selementsvia Enumeration 's hasMoreElements() and
nextElement() methods.
Search WWH ::




Custom Search