Saturday, November 13, 2010

Generics in Java

Generics introduced in J2SE 5.0. Generics introduced for Collections. Collection store Objects and any type of object can be store in collection. When a stored object pulled back from collection it required to cast that object. Compiler does not check the type at compile time. Type Cast can be failed at runtime.

Generics allow particular(Unique but similar) types of object to save in Collections. If wrong type of object added in Collections the program will fail at compile time. Generics provides Type Safety, No Types Cast Required.

Earlier Example of Collection

Vector vc=new Vector();
vc.add("Pakistan");
String s=(String)vc.get(0);       -- "Required Type Cast"

Generics Example

Vector<String> vc=new Vector<String>();
vc.add("Pakistan");
vc.add("England");
String country=vc.get(0);         -- "No Type Cast"




List<String> list=new ArrayList<String>();
list.add("Pakistan");
list.add("England");
String country=list.get(0);         -- "No Type Cast"

String vs StringBuilder vs StringBuffer

Strings are immutable objects which means once String object is created, it can never be change. Whenever there is some change in String's value. A new object of String is created in heap.

String str="hello";
String str=new String("hello");

StringBuffers are mutable objects.StringBuffer are continuous sequence of characters. StringBuffers are Thread Safe.

StringBuffer str=new StringBuffer("zulqarnain");

StringBuilders are mutable objects. StringBuilders are not Thread Safe
.
StringBuilder str=new StringBuilder("hello");

Why and when Using StringBuffer and StringBuilder

StringBuffer and StringBuilder should be used when lot of modification requires in string characters .
If continuous changes required in string character and using String  object you are making waist of memory (String pool objects).