Java / Generics
Explain Generics using a sample code.
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.
In the above code, the example is rewritten using generics, and the list is strongly typed that requires no casting.
More Related questions...