Collection Framework


Sun has parameterized all collection classes in the Collections Framework. A simple language-based test demonstrates a simple use of the parameterized type ArrayList:

 final String name = "joe"; List<String> names = new ArrayList<String>();    // 1 names.add(name);                                 // 2 String retrievedName = names.get(0);             // 3 assertEquals(name, retrievedName); 

Both the implementation class ArrayList and the interface List are bound to the String class (line 1). You can add String objects to name (2). When retrieving from name and assigning to a String reference (3), you need not cast to String.

If you attempt to insert an object of any other type:

 names.add(new Date()); // this won't compile! 

the compiler will present you with an error:

 cannot find symbol symbol  : method add(java.util.Date) location: interface java.util.List<java.lang.String>       names.add(new Date()); // this won't compile!            ^ 



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net