Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
out.print(paramName);
}
From the above code I don't understand why the typecast of paramNames.nextElement()
to String is necessary. Can some one explain this?
When I pass the parameter name from a form it is already in a String, then why do we use (String)
?
Enumeration
is a generic type, and should typically be used with a proper generic parameter. For example an Enumeration
of String
s:
Enumeration<String> paramNames = ...;
This makes the signature of the nextElement()
method look like this:
public String nextElement();
The reason they cast to a String
is because that without a generic parameter, the compiler treats it as if you'd typed:
Enumeration<Object>
So the return type of nextElement()
becomes Object
, and you can't just assign an object to the String
variable paramName
.
Of course, if request.getParameterNames()
doesn't return Enumeration<String>
, but just Enumeration
, then you can't do any better than that.
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