Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary to cast an enumeration element to a String when printing it out?

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)?

like image 470
user3479162 Avatar asked Sep 04 '25 01:09

user3479162


1 Answers

Enumeration is a generic type, and should typically be used with a proper generic parameter. For example an Enumeration of Strings:

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.

like image 111
Jamie Cockburn Avatar answered Sep 06 '25 15:09

Jamie Cockburn