InterviewSolution
| 1. |
Benefit of Generics in Collections Framework? |
|
Answer» Generics were introduced to deal with type-safe objects in J2SE 5. Only specific TYPES of objects can be stored in Collections as forced by Generics. Some of the benefits of Generics in Java are given as FOLLOWS: Elimination of type casting Type casting is not required after the advent of generics. An example that demonstrates this is as follows: Before generics type casting was required. List l = new ArrayList(); l.add("apple"); String str = (String) list.get(0); // type casting After generics type casting was no longer needed. List<String> l = new ArrayList<String>(); list.add("apple"); String str = list.get(0); // no type castingChecking at COMPILE time Compile time checking is PROVIDED so that there is no problem at run time as it is much better to handle a problem at compile time than at run time. An example that demonstrates this is as follows: List<String> l = new ArrayList<String>(); l.add("apple"); l.add("MANGO"); l.add(98); // This will lead to a Compile Time ErrorType-Safety Generics result in type safety as only a single type of object can be held in them. This means that other types of objects are not allowed. |
|