Reputation: 21
I have a HashMap
as below:
public static HashMap submitService(HashMap inputMap) throws Exception
{
//code....
ArrayList<String> allIdsList = (ArrayList<String>) inputMap.get("Result_List");
// System.out.println("Result List: " + allIdsList); prints the arraylist (e.g. [2, 21, 6, 3]
for(int i=0;i<allIdsList.size();i++)
{
System.out.println(" values: " + (String)allIdsList.get(i));
}
}
the arraylist
is printing in the console(I tried it only to see if the list is not empty). But for (String)allIdsList.get(i)
inside the for loop following error message is coming
java.lang.Long cannot be cast to java.lang.String
Would really appreciate someone's help.
Upvotes: 1
Views: 111
Reputation: 188
It looks like allIdsList
is of type ArrayList<Long>
but you are using ArrayList<String>
.
You can change the type of allIdsList
to either ArrayList<Long>
or remove the generic and use ArrayList
.
Upvotes: 0
Reputation: 20159
Where is this inputMap
coming from? By the looks of it, its values are not of type ArrayList<String>
but something like ArrayList<Object>
or even ArrayList<Long>
. The problem seems to be somewhere outside your posted snippet.
Since you're working with raw types in this method, the compiler won't complain (although it should warn you about using raw types). However, the VM will throw a ClassCastException
where the cast fails - that's what you're seeing.
Try strengthening your signature by only accepting HashMap<String, ArrayList<String>>
as inputMap
. That way, you can get rid of those awful casts, as you now get compile time type checks. In the best case, this will give the compiler enough information to point out where you're calling this method with an incorrectly typed inputMap
. You should then be able to easily fix the error merely by following the compiler's instructions. If that doesn't work, you're probably using raw types in your calls as well and you'll need to dig down the stack trace to fix those.
Upvotes: 0
Reputation: 1332
Make sure HashMap is of type HashMap<String,ArrayList<String>>
Upvotes: 1
Reputation: 525
Try this:
public static HashMap<String,ArrayList<String>> submitService(HashMap<String,ArrayList<String>> inputMap) throws Exception
{
//code....
ArrayList<String> allIdsList = inputMap.get("Result_List");
for(int i=0;i<allIdsList.size();i++)
{
System.out.println(" values: " + allIdsList.get(i));
}
}
Upvotes: 0
Reputation: 1967
Replace: public static submitService(HashMap<'String,ArrayList<'String>> inputMap) throws Exception
Looking at the exception, its sure that the parameter passed does not have arraylist of string.Looks like it might be ArrayList<'Object>(with long value present in the list which eventually is casted in String) or Arraylist<'Long>.
Upvotes: 0