Wednesday, March 05, 2014

Generics in Java

Lets take an example and try to understand generics

package helloworld;

import java.util.*;

public class CollectionsTest {
public CollectionsTest() {
super();
}

public static void main(String[] args) {


List var = new ArrayList();

var.add("Arpit");
var.add("Rahi");

// Loop over it and print the result to the console
for (Object s : var) {
System.out.println(s);
}
}
}

If you will run this code you will get following result

Arpit
Rahi

Now lets suppose you want to get the result all in CAPS that is capital letter.

In order to convert the result to capital you might need a function toUpperCase() but can you apply this to the object s directly , the answer is no .

you will first need to typecast the object s to string and then you will have to use the function toUpperCase() to convert it to capital letter i.e. now your code will look like this

package helloworld;

import java.util.*;

public class CollectionsTest {
public CollectionsTest() {
super();
}

public static void main(String[] args) {


List var = new ArrayList();

var.add("Arpit");
var.add("Rahi");

// Loop over it and print the result to the console
for (Object s : var) {
System.out.println(((String)s).toUpperCase());
}
}
}


As you can see we have explicitly type cast the object ((String)s) to use the function this is because the collection return the element as object.

Now we will see how generics will come into picture.

Generics allows you to define the type of object in angle brackets after the collection class name.


So now our revised code will be

package helloworld;

import java.util.*;

public class CollectionsTest {
public CollectionsTest() {
super();
}

public static void main(String[] args) {


List<string> var = new ArrayList<string>();

var.add("Arpit");
var.add("Rahi");

// Loop over it and print the result to the console
for (String s : var) {
System.out.println(s.toUpperCase());
}
}
}

As you can observer we have specified the type of collection in the angel bracket
List<string> var = new ArrayList<string>();

So while displaying the result we need not explicitly type cast it back to string.

No comments: