Arrays


You cannot create arrays of bounded parameterized types:

 List<String>[] names = new List<String>[100]; // this does not compile 

Attempting to do so generates the compilation error:

 arrays of generic types are not allowed 

Again, the problem is that you could easily assign the parameterized type reference to another type reference. You could then add an inappropriate object, causing a ClassCastException upon attempted extraction:

 // this does not compile List<String>[] namesTable = new List<String>[100]; Object[] objects = (Object[])namesTable; List<Integer> numbers = new ArrayList<Integer>(); numbers.add(5); objects[0] = numbers; String name = namesTable[0].get(0); // would be a ClassCastException 

Java does allow you to create arrays of parameterized types that are unbounded (i.e., where you use only the wildcard character ?):

 public void testArrays() {    List<?>[] namesTable = new List<?>[100];    Object[] objects = (Object[])namesTable;    List<Integer> numbers = new ArrayList<Integer>();    numbers.add(5);    objects[0] = numbers;    try {       String name = (String)namesTable[0].get(0);    }    catch (ClassCastException expected) {    } } 

The chief distinction is that you must acknowledge the potential for problems by casting, since the List is a collection of objects of unknown type.



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