java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String When using HttpServletRequest getParameters()

I got the following error when trying to read a HttpServlet.getParameterMap(). Using the following code.

Map map=request.getParameterMap();
if(map.contains(key)){
String value=(String) map.get(key);
}

java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String]

HttpServletRequest.getParameters() according to the javadocs returns an object of Map with the following attributes.

From the Java docs

“””
Returns:

an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

“””

So what it means is that it actually returns a type of Map<String,String[]> instead of Map<String,String>. So the correct defination is map.get(key) returns a String[] not a String. This is because request.getParameter(key) returns a String which is actually the first element of the resulting string array.

Have no idea why the designers design it this way. So to be safe, you can use the following to ensure that you will always use the correct type of map from a HttpServletRequest object.

Map<String,String[]> map=request.getParameterMap();

So read your javadocs carefully when you get weird ClassCastExceptions.

About these ads
Explore posts in the same categories: Tips

Tags:

You can comment below, or link to this permanent URL from your own site.

2 Comments on “java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String When using HttpServletRequest getParameters()”

  1. Alfred Says:

    Thanks for the solution, Stephen..
    u save my days.. :)


  2. [...] java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String When using Http… January 2009 1 comment 3 [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: