问题
I was doing some past papers on my exam and I came accross this question :
What does (String) do on line 5 and what is this type of expression called?
Here is line 5 : String str = (String) D.dequeue ();
My guess is that it's veryfing if the value we get from D.dequeue() is a String though I am not sure.
回答1:
This is called Casting. The value returned by the Dequeue method is cast to a String type.
Essentially this operation forces the value to take the type of String so that you can assign it to a variable which is also of type String. You should note however that casting from one type to another may not always succeed.
For example, this will give you a compile-time error:
int a = (int)"123";
回答2:
String str = (String) D.dequeue ();
It's called typecasting. Since you are not using generics you are required to typecast the Object before using it as String.
回答3:
It's actually making an explicit cast of the object returned by D.dequeue() to String (i.e. transforming it into a String instance). Take a look at this explanation: Casting objects in Java
来源:https://stackoverflow.com/questions/23594026/java-string-what-does-it-do