Generics Part-1 - Introduction: Case 1: Type Safety
Generics Part-1 - Introduction: Case 1: Type Safety
But Collections are not type safe that is we can’t give the guarantee for the type of elements
present in the collection.
For example if our program requirement is to hold only String type of Object. If we choose AL by
mistake if we are trying to add any other type of objects we won’t get any compile time error.
But program may fail at runtime.
We can’t give the guarantee for the type of elements in the AL. So collections are not safe to type
caste.
Case 2:
Type Casting:
In the case of Array, At the time of retrieval it is not required to perform type casting because
there is a guarantee for the type of element present in the Array.
Arrays type casting not required, but in the case of collections at the time of retrieval compulsory
we should perform type casting because there is no guarantee for the type of elements present
inside collection.
Need of Generics:
By mistake if you are trying to add any other type then we will get compile time error.
Conclusion 2:
For the type parameter we can provide any class or interface name but not primitive. If we are
trying to provide primitive then we will get Compile time error.
AL implementation in 1.4 version:
Until 1.4 version a non-generic version of AL is declared as follows.
The return type of get method is Object. Hence we have to perform type casting.
A generic version of AL class is declared as above.
Based on our requirement we can define our own generic classes also.
But within the method we can add only string type of objects to the list. By mistake if we are
trying to add other type then we will get compile time error.
m1(AL<?> l):
1. we can call this method by passing AL of any unknown type.
2. But within the method we can’t add anything to the list except null. Because we don’t know
the type exactly.
3. null is allowed because it is valid value for any type.
These type of methods are best suitable for read only operation but not for write operation.
Within the method we can add X type of Object and null to the list.
Rules on ?:
Right hand side ? character not allowed
Part-5 || generics method
All the right-hand side are equal since the generic syntax is removed at the compile time only.
The following declarations are equal