Java / Generics
Explain Generics using a sample code.
List list = new ArrayList(); list.add("No Generics is used "); String s = (String) list.get(0);
In the above example, ArrayList can hold any type of objects, however we need to cast each object to its appropriate data type since get method's return type is Object. A string literal is added to the list and to get it from the list we need cast and store it.
If we store an employee object for example at the first index, then the 3rd line of code will throw a run-time Exception.
List<String> list = new ArrayList<String>(); list.add("Generics is implemented"); String s = list.get(0); // no cast is required
In the above code, the example is rewritten using generics, and the list is strongly typed that requires no casting.
More Related questions...