Can generics be used in lists in Java 1.4?

I need to use Java 1.4 and use arraylist structures. Now I need to do re-factoring, and this will help if I can use Generics. I currently have code like this

ArrayList rows = new ArrayList();

This is a simple ArrayList. But now the "rows" variable is becoming more complex and needs to define a "Row" class. Now I want to do something like what you see in J2SE 1.5

ArrayList<Row> rows = new ArrayList();

Thrall through Google does not provide answers without any complicated use of third-party solutions. How should my code change to host this in 1.4, without using third-party open source solutions / projects (if possible)?

+5
source share
5 answers

Generics were introduced in JDK 1.5. Therefore, you cannot use them in 1.4. However, you can use the JDK 1.5 compiler, but specify 1.4 with your classes with the -target 1.4javac option , while preserving the parameter -source 1.5to indicate that your source is compatible with 1.5. In this case, you can use generics, since they should not affect the result classes.

See Cross Compilation Options

+9
source

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();
    // Do something with the row.
}

Java 1.5 . , , , . , ( , , ):

for(Row row : rows) {
   // Do something with the row
}

, 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;
    // Do something with the row.
}

, , . - , , , ClassCastException JVM

+3

, . 1.5

javac -target jsr14 ............

java 1.4, .

, 1- . , Enums , 1.5. , .

+2

No, you cannot use them in JDK 1.4. They were introduced in JDK1.5

0
source

All you have to do is drop them. This may mean a run-time exception if you put the β€œwrong” types in the list.

Row arow = (Row) rows.get(0);

for ($i=0; i<rows.size(); $i++){
    Row element = (Row) rows.get($i);
    element.printCells();
    (...)
}
-1
source

All Articles