Generics tends to solve the problem of what I consider "naive casts" in Java 1.4 or earlier when working with collections. In Java 1.5+, the line you posted:
ArrayList<Row> rows = new ArrayList();
will give a warning, the corresponding common code
ArrayList<Row> rows = new ArrayList<Row>();
This tells the compiler that your ArrayList should only contain a string type.
, Java 1.5 , , :
ArrayList rows = new ArrayList();
Generics, , - generics - - 1.5 1.4 ( / , ), ArrayList, .
1.5 .
1.4, , ArrayList. :
for(Iterator rowIterator = rows.iterator(); rowIterator.hasNext(); ) {
Row row = (Row) rowIterator.next();
}
Java 1.5 . , , , . , ( , , ):
for(Row row : rows) {
}
, ArrayList, , . , ArrayList (, , , ArrayList, , , , ArrayList , - , , - , ).
ClassCastException ( , ):
for(Iterator rowIterator = rows.iterator(); rowIterator.hasNext(); ) {
Object shouldBeRow = rowIterator.next();
if(!(shouldBeRow instanceof Row)) {
throw new ClassCastException("The object " + shouldBeRow + " is not an instance of Row - only Rows should be present in the list!");
}
Row row = (Row) shouldBeRow;
}
, , . - , , , ClassCastException JVM