This is the code from my textbook:
Stack<String>[] a = (Stack<String>[]) new Stack[N];
My questions are:
Why do you have to do type conversion on the new stack array created? I tried it with just
Stack<String>[] a = new Stack[N];
and it compiled and ran fine. Even after pushing Strings into a and printing the pop method. Also, pushing a int in would immediately give me a compiler error so why is it necessary to type cast it to
Stack<String>[]
specifically?
2) Type casting is not required: There is no need to typecast the object. Before Generics, we need to type cast. After Generics, we don't need to typecast the object.
To sign off, learning Java typecasting is necessary for becoming a successful developer or programmer. The intent is to define functions and then ensure variables within the communication are performing as per the end-functionality.
The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.
As mentioned previously, generics can eliminate the requirement for casting.
You can not create arrays with parameterized type (see Restrictions on Generics). So you can not use ... = new Stack<String>[N]
.
Using ... = new Stack[N]
will work but you will have a warning for unchecked convertion (use -Xlint
in javac to see the warning).
So the only proper way is to create the array with a raw parameter and then to apply a checked cast to the wanted type.
Not sure what you mean by that question, but if you mean why not new Stack<String>[N]
it is because java arrays does not support parameterized array creation.
Because of my answer in (1) the created array is not parameterized, but you are assigning it to a parameterized variable. And therefor the optional, but preferred checked cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With