Advantages Of Generic Over Array
Posted By : Kishor Kumar Singh | 30-Apr-2018
For example- If our Programme requirement is to add any string object then we can go for string array. For this way we can add only string type of objects, by mistake if we are trying to add any other type, we will get compilation error.
String s = new sr=String; s = “Java”; // correct s = “Automation” // correct s = new Student(); // wrong
Hence, in the case of the array, we can give the guarantee about the type of elements.
String array contains any string objects. Due to this arrays are always safe to use w.r.t type.
But collections are not safe w.r.t type.
In the case of arrays at the time of retrieval, it is not required to perform any type casting
Compile time error is received in case typecasting is not performed for collections at the time of retrieval.
Hence, in the case of collection typecasting is mandatory which is a bigger headache for the programmer.
To overcome the above problems of collections Generic concepts is included in 1.5 version.
Hence, the main objectives of Generics concepts are-
(1) To provide Type safety to the collection, so that they can hold only a particular Type of objects.
(2) To resolve typecasting problems
(3) At the time of retrieval, it is not required to perform any typecasting
For example- To hold any string type of objects a generic version of ArrayList we can declare as follows-
L = new ArrayList ();
For this ArrayList, we can add only String type of objects, by mistake if we are trying to add any other type we will get a compilation error.
i.e. we are getting type safety.
L.add(“Java”); L.add(“Automation”); L.add(“10”);
At the time of retrival it is not required to perform any typecasting.
String name = L.get(0);
Usage of Parent class reference to hold child class object is considered as Polymorphism.
Polymorphism concept is applicable only for base type but not for parameter type.
Kishor Kumar Singh
Kishor Kumar Singh is highly dedicated towards work and he is a great team player. He believes that “No amount of testing can prove a software right, a single test can prove a software wrong".