InterviewSolution
| 1. |
How Generics Changed The Collection Framework? |
|
Answer» With JDK5 the COLLECTION FRAMEWORK was reengineered to add generics. That was done to add "Type Safety" to the collections. Prior to JDK5 (and generics) elements were stored in collections as Object references, which brought the danger of ACCIDENTALLY storing incompatible types in Collection because for Collections everything was Object reference. Which would have resulted in run time error when trying to retrieve elements and casting them to the desired type. With the introduction of generics now we can explicitly tell which data type is to be stored in the collections, which helps in avoiding the run time error. As Collection will throw error at COMPILE time itself for incompatible data type. As exp. Map<String, String> cityTemperatureMap = NEW LinkedHashMap<String, String>(); Here we are explicitly stating that this LinkedHashMap can only store string as both key and value. With JDK5 the Collection framework was reengineered to add generics. That was done to add "Type Safety" to the collections. Prior to JDK5 (and generics) elements were stored in collections as Object references, which brought the danger of accidentally storing incompatible types in Collection because for Collections everything was Object reference. Which would have resulted in run time error when trying to retrieve elements and casting them to the desired type. With the introduction of generics now we can explicitly tell which data type is to be stored in the collections, which helps in avoiding the run time error. As Collection will throw error at compile time itself for incompatible data type. As exp. Map<String, String> cityTemperatureMap = new LinkedHashMap<String, String>(); Here we are explicitly stating that this LinkedHashMap can only store string as both key and value. |
|