Generic in java 1.5 tutorial
To create collection with type safe object generic is used, it can reduce unnecessary cast in our application , Avoid type cast may be caused by operational errors, this tutorial compares the difference between 1.4 and 1.5 version of jdk
Old Syntax:
ArrayList o=new arrayList();
o.add(new Integer(3));
o.add(new Integer(4));
int i=((Integer)(list.get(0))).parseInt();
New Syntax:
ArrayList<Integer> o=new ArrayList<Integer>();
o.add(new Integer(3));
o.add(new Integer(4));
int i=(list.get(0).parseInt();
To learn more on Generic you can choose Java Training or Java Tutorial
Example:
public class JdkGeneric<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
JdkGeneric<Integer> integerBox = new JdkGeneric<Integer>();
JdkGeneric<String> stringBox = new JdkGeneric<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
Output
Integer Value :10
String Value :Hello World
No comments:
Post a Comment