Reputation: 487
Running my code results in the following error: java.lang.Integer cannot be cast to java.lang.String
This is what I have:
for(Map<String, Object> record: list) {
if(((String)record.get("level")).equals("1")) {
rootList.add(record);
}
}
I have tried converting that little snippet to an Int using toString but it just gives me a compiling error. I'm new to java (and I did not write this code either) so forgive me if it's a stupid mistake.
Upvotes: 0
Views: 122
Reputation: 8376
Well, if the Map
values are Integer
s, then toString()
should work for converting them to strings:
for(Map<String, Object> record: list) {
if(record.get("level").toString().equals("1")) {
rootList.add(record);
}
}
Upvotes: 0
Reputation: 129507
Your Map
s holds values of type Object
, meaning they can really hold anything as values (since everything extends Object
); there's no guarantee that a given value will be a String
. By your error, it would appear that one of the values in one of your maps is an Integer
, which evidently cannot be cast to a String
. The quick-fix is to use toString
:
record.get("level").toString().equals("1")
But note that this will yield true for any object whose toString
returns "1"
, not just strings. If you want to only check for equality with the string "1"
, then you can use "1".equals(...)
, since equals
can take any object as an argument.
Upvotes: 5
Reputation: 240890
try
Object number = record.get("level");
if("1".equals(number)){
}
Upvotes: 2
Reputation: 71
try one of this alternatives:
rootList.add(record + "");
or
rootList.add(new String(record));
Upvotes: 0