Generics

  • The java Generics features were added to the java language from java 5/JDK 1.5.
  • Before Generics ,we could put any thing in any ArrayList, LinkedList, Vector, HashSet, TreeSet, LinkedHashSet, HashMap, TreeMap, LinkedHashMap, HashTable

  • Collection without Generics
    Non Generics
  • Casting code may generate warning about "unsafe cast".

Example to show non generics code

import java.util.ArrayList;
import java.util.List;
class Employ
{
	Integer cid;
	String name;
	String address;
	Employ(Integer cid,String name,String address){
		this.cid=cid;
		this.name=name;
		this.address=address;
	}
	@Override
	public String toString() {
		return "Customer [cid=" + cid + ", name=" + name + ", address="
				+ address + "]";
	}
}
public class NonGenericsDemo {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(new Integer(100));
		list.add("hello");
		list.add(new Employ(111,"john","New York"));

	//Taking out the objects from the ArrayList
		Integer integer=(Integer)list.get(0); //type casting to Integer
		System.out.println(integer);
		String string=(String)list.get(1); //type casting to String
		System.out.println(string);
		Employ employ=(Employ)list.get(2); //type casting to Employ
		System.out.println(employ);
	}
}
	

The above program is an example of non-generics collection that is complier shows the "unsafe cast" warning while type casting the object into its proper type. Many times programmer is not aware that what type of object is stored in the ArrayList or other collections like HashSet, HashMap etc, that causes the ClassCastException at runtime.