Generics Continued

There are different ways to use generics. Before seeing that lets revisit the syntax for creating an instance of a generic class :

class-name<parameter-type> objectName = new class-name<parameter-type>();

As we saw in the previous post, we can use the following syntax for creating an ArrayList with Generics :

ArrayList<String> s1 = new ArrayList<String>();s1.add("Sandeep");s1.add("Ravi");
for (String s:s1) {
    System.out.println(s);}

Apart from using ArrayList as the reference type, we can also use List as the reference type as follows :

List<String> s2 = new ArrayList<String>();s2.add("Sandeep");s2.add("Ravi");
for (String s:s2) {
    System.out.println(s);}

What this means is that we can use the reference of a parent class to hold the child object. Generics supports that.

Lets try to use generics with primitive types:

List<int> i1 = new ArrayList<int>();i1.add(1);i1.add(2);
for (int i:i1) {
    System.out.println(i);}

This will result in compilation error. Saying required : reference got int.
That means we cant use generics with primitive types.

Another thing is that parent references can only be applied to Classnames and not parameter types. Lets try the following :

List<Object> s3 = new ArrayList<String>();s3.add("Sandeep");s3.add("Ravi");
for (String s:s3) {
    System.out.println(s);}

The above code will give a compilation error saying : incompatible data types.

The code for the above examples can be found here.

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures