Rule7:Use Varargs with generics cautiously
Note : as contracct to array of generics being illegal . varargs of generics or parametrized type is legal (intentionally left by java library developers as it’s thought to be very useful) .many java libraries itself uses varargs of generics e.g. AArray.asList(T .. a)
Internal of Varargs :
internally varargs is stored as array and array has different type rules from generics so it is not safe
Case :Never expose generic varargs methid to be invoked by untrusted external code.
public void returnArray(T ... a){
if(a.lenth==3)
return Array.asList(a[0],a[1])
}
//calling generic varargs from external untursted source causing error:
class GenericTest{
psvm(String as[])
{
//error on run time ClassCasteException
String[] arr=returnArray("Seva","Anand","Sevanand');
}
}
Explanation:
in parameterized type/generic method the compiler resolves the type to be Object[] to be generic in which every other can be accommodated.
but during calll the arr is of String Which is not a subtype of Object .so ,it complains .
Application :
1.If in some code varargs with generics is used ensure not written to be illegal i.e complains at client side if case 1 is there.
2.ensure @SafeVarargs is used on method only if there is surity from programmer after testing it to be safe .
3.If possible Use List in place of varargs ,it will have a bit less performance but will provide more reliable .