Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Type Casting Necessary?

This is the code from my textbook:

Stack<String>[] a = (Stack<String>[]) new Stack[N];

My questions are:

  1. Why is it "new Stack[N]"?
  2. 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?

like image 593
Myang310 Avatar asked Apr 01 '16 22:04

Myang310


People also ask

Is type casting required for generics?

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.

Is type casting important in Java?

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.

Can you cast generic type Java?

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.

Does generics eliminate the use of casting?

As mentioned previously, generics can eliminate the requirement for casting.


2 Answers

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.

like image 190
zer0chain Avatar answered Oct 12 '22 13:10

zer0chain


  1. 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.

  2. 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.

like image 28
gustf Avatar answered Oct 12 '22 13:10

gustf