A general data structure created gives a compilation warning with JDK 1.5
Vector vect = new Vector();
To the above vect object any Java data can be added as follows.
The vect object stores int, double, boolean and string values. This is fine, no problem if the programmer would like to add any data type or object. If the programmer would like to add only integers or strings, he must check explicitly with some validation code. To avoid this extra validation code, the JDK 1.5 introduced a concept called generics. In generics, the validation code is written by the data structure itself.
vect1 = new Vector ();
The above Vector object vect1 stores only integer values. If other added, it is compilation error.
vect1.add(10); // works fine
vect1.add(10.5); // compilation error
vect1.add("hello"”"); // compilation error
Let us see another data structure ArrayList that stores only strings.
al.add(“hello”); // works fine
al.add(10); // compilation error
al.add(10.5); // compilation error
Creating a data structure to accept only one type data is known as generics. Generics give type-safe operation. If the programmer designs a non-generic data structure, the compiler displays a warning "unchecked and unsafe operation". Finally to say, generics allow storing only one type of data and this avoids validation code. Generics make implicitly checked and safe operation.
3. Enhanced for loop
Earlier before JDK 1.5, programmer write a for loop to print the elements of a data structure.
for(int i = 0; i < vect.size(); i++)
The above for loop known as basic for loop includes incrementing and condition checking. To avoid this, to print the values of a data structure or array, JDK 1.5 comes with a simple for loop known as enhanced for loop or foreach loop. This avoids incrementing and condition checking.
for(int k : vect)
For every iteration, one element of vect is copied into k and k is printed.
To discuss very clearly about this new loop, two programs are given using with arrays and data structures.
Pass your suggestions to imporve the quality of this tutorial "Data Structures JDK 1.5 Features".