Friday, January 05, 2007

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

Very simply, you get the exception
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
when you try to cast an array kind of a class to the linear type. In this case, attempting to cast String -> String[] or vice versa will cause the JVM to throw this particular exception at runtime. Compilers cannot catch this oversight.
As an example, consider an attempt to read all parameters passed to a servlet using the request object. The parameter map can be obtained with:
Map parameters = request.getParameterMap();

From HTML basics, we know that parameters are passed as key/value pairs of Strings to the web server, so the temptation is to assume that the generics mapping for parameters is <String, String>. In fact, compilers will allow you to use this generic:
Map<String,String> parameters = request.getParameterMap();
for(String key: parameters.keySet()) {
String value = parameters.get(key); // error happens here
System.out.println(key + "=" + value);
}

This code snippet will compile and run fine, producing results that look like:
firstName=[Ljava.lang.String;@1fe49b5
lastName=[Ljava.lang.String;@1993b4f
This is assuming parameters passed to the servlet (or JSP) include ones named 'firstName' and 'lastName', of course.

As it turns out, the value side of the parameter map is actually a String[] type. So the proper generic for this map is
<String, String[]>. When you call request.getParameter("firstName");, it simply returns the equivalent of parameters.get(key)[0];, which reads the first value associated with the key. This happens even if your form might have sent single-dimension parameters for processing.
So, just remembering the map's generics mapping may save you a lot of headaches down the road. This is simple Java internals - but a look at forums on the web shows how much of a problem this is for programmers out there. You's get the same kind of exception if you attempted to cast Date to Date[] (which would throw java.lang.ClassCastException: java.util.Date cannot be cast to [Ljava.util.Date;).

81 comments:

Marco Massenzio said...

Hole in one!

Thanks for the tip, it did solve the mysterious message ;-)

Best wishes,
Marco.

mauhiz said...

The problem is that most of J2EE is still not generics compatible...

Anonymous said...

awesomme post!!!

Am really thankful for the tip....it resolved my issue. i wasted 2 weeks to find out the cause....U r the man

Anonymous said...

This bad boy saved me. Thanks

ski.rulez said...

good tip :) thx

haiko said...

got the exception also with the ParamMap from a Servlet. Thanks for mentioning it.

Pablo said...

vv helpful. thx.

en3rgizer said...

nice tip, helped me to solve the problem

Anonymous said...

AWSOME DUDE!
II love you now1

Diablo said...

Thanks alot buddy.. your tip is very much helpful for me. you solved my problem.

Anonymous said...

Thank you!
That's the "nuts and bolts" that are missing very often ....
:-)

And: it's a pleasure to read blogs that provide well-founded knowledge in a good writing.
Also that is missing in many other places on the web ...

Anonymous said...

Thanks friend. You saved my time a lot.

Vano said...

Thank you!!!

andcoder said...

Thanks.. that solved my problem

Anonymous said...

Thanks for the help!

Naveen said...

1 public String[][] getTableContent(StatelessGuiSubitemTestObject tableObj){
2
3 ITestDataTable currentTable = (ITestDataTable)tableObj.getTestData("contents");
4
5 String tableContents[][] = new String[6][5];
6 int row, col = 0;
7 for (row =1;row < currentTable.getRowCount();row++)
8 {
9 for (col = 1;col < currentTable.getColumnCount();col++)
10 {
11 tableContents[row][col] = currentTable.getCell(row, col).toString();
12 }
13 }
14 return tableContents;
15 }


Here in the 14th step when I try to return the tableContents, I am getting this type of error:[[Ljava.lang.String;@7dcc7dcc


Could you please help me out?

Waqas Ahmed said...

But what is a solution to this problem. I am facing same error, how can i finally get the real value into String object.

Jerome Eteve said...

Great tip !

I was struggling with that the whole afternoon :)

Cheers.

Jerome

fnu said...

Thanks a lot for the information..
Problem solved..:)

panstern said...

Thanks too!

You helped me saving a lot of time I guess;)

Anonymous said...

Oh my god this was such an annoying snag. Thanks so much!!!

Simer said...

Thats a great post!!!!
Thanks

Anonymous said...

Thank you for the tip!

Anonymous said...

Thanks a lot, i spent long time with this problem

Anonymous said...

thanks a lot

said...

thanks a lot

ashucl said...

Thanks solved my problem....!!!

kumaraswamycv said...

Ofcourse, as others, You saved my time dude....

kumaraswamycv said...

Ofcourse, You saved my time dude.... thanks man.

kumaraswamycv said...

Ofcourse, you saved my time

Vinay said...

Thanks Boss. Good Blog. Its helping a lot.

Anonymous said...

And yes, I also stumbled over this!
Thanks

Aditi said...

Thanks a lot! Was just stuck up with this!

rojesh said...

I am still a java student and i am running into same problem when i am trying to caputure a request parameter.

I have
pmap.get("query_number");
which i want to be capture as integer. But when i try this

int resultNum=(Integer.parseInt((String)pmap.get(query_number)));

i get:

java.lang.ClassCastException: [Ljava.lang.String;

But when i print out it prints out its value just fine.

Thanks in advance.

Anonymous said...

Use something like this to get the actual value,

System.out.println(" selectOneRadio3 " + String.valueOf(par.get("selectOneRadio3")));

Vaishu said...

I am having the same issue and also dud as per the suggestion still no use.. Need help
tring[] split = deptId.split(",");

boolean validParam = false;
// check whether the locationID is a valid locationID for the user
List departments = DierbergsToolsService.fillDeptCosting(connectionString,userName,keyMasterUrl);
Map userDeptList = new LinkedHashMap();

if(split[i].contentEquals((String)userDeptList.get("dept"))){
System.out.println("In Valid ");
validParam =true;
break;
}



And the dept id is in the form of "3, 9". It gives me classcast exception in line for if statement from Short to the String as from DB I think so the values are coming as Short.

Anonymous said...

thank you! This save my time!

Anonymous said...

Thanks For the tip.

Anonymous said...

you're my man! thx a lot.

Anonymous said...

Thanks,

Laura

Joel said...

Thanks, saved my day too

biznuge said...

Thanks. I'd estimate that was around 2 hours of my life you just saved me...

Cheers for that!!!!

Anonymous said...

Thank you! It just resolved my question. Amazing!

Anonymous said...

very helpful, thanks for the information.

Adheesh L P said...

Thanks, that indeed was helpful!

T said...

Thanks, buddy. Got me quickly out of a jam.

George Jempty said...

Kudos! I pasted my error and this was the first google result, and I was specifically trying to dereference a request/parameterMap entry, so it was spot on.

Anonymous said...

just what I was looking for. Thanks!

boulet-sensei said...

You saved my life ! thanks !

Sandeep said...

Amazing .. Thanks

Anonymous said...

Saved my day, Thanks

Zack said...

Nice work. First google result was yours and it was exactly what i was doing wrong. Thanks!

Anonymous said...

As someone else who has just had hours of his life saved, I'm trying to think if I've seen a more appreciated post!

Thanks!

Anonymous said...

Man, you're ROCK!!!
Thanks!

Anonymous said...

Eres lo máximo.
Gracias.

Loïc said...

Man, thank you very much. Thanks to you, i solved the problem in 5 minutes. By myself it would have taken weeks to figure it out, cause I was realy clueless.

Anonymous said...

Thanks Heaps,
Saving my 1 days work.

paradox said...

thnks for the post

Girish Wakure said...

Thank you very much!!

pking said...

Thx Man! Your hint saved me a lot of time.


Greetings from Poland,
PK

hisham said...

Thank you very much.

saul_berardo said...

guy, you saved my night, thanks! =D

Anonymous said...

Well written, many thanks.

Tricky problem, bloody Map.

Anonymous said...

Awesome Work dude......good post.

Anonymous said...

Thanks for the Tip. I was just trying to debug something and this helped fix the getParameterMap !

- Gautham

Sunil Kumar Das said...

Thanks Mate. I had already busted my mind for more than a half day in finding the fix for the issue, "struts2 ognl exception for the setter method Ljava.lang.String...". Thanks a lot again for valuable tip

Anonymous said...

Thanks for sharing. It helped me.

Tonky said...

Thanks for the tip. It solved my problems and saved me a bunch of time!

sureshreddy said...

Nice post...!!

Nicholas Grealy said...

Helped me, thank you!

Anonymous said...

Thank You Very Much... It saved my Hours..

Lumination said...

You're my hero!

Anonymous said...

Thanks, 5 years later still saving me time & teaching me lessons! =)

Anonymous said...

Awesome. Thank you!

Anonymous said...

Thanks!

Anonymous said...

Knowledgeable. Well communicated.

Jubz for the win!

Sumit Bharati said...

It was a great help.

Anonymous said...

Thank you very much. Good help. 7 years left, but it is actual!

Anonymous said...

really nice and very useful article, thanks a lot.

ArnabRaxit said...

Thanks for the tip :)

Anonymous said...

Thanks a ton! saved my day!!