Envious
Envious

Reputation: 487

Int cannot be cast as String issue at runtime

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

Answers (4)

GriffeyDog
GriffeyDog

Reputation: 8376

Well, if the Map values are Integers, 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

arshajii
arshajii

Reputation: 129507

Your Maps 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

Jigar Joshi
Jigar Joshi

Reputation: 240890

try

Object number = record.get("level");
if("1".equals(number)){

}

Upvotes: 2

Jairon Alava
Jairon Alava

Reputation: 71

try one of this alternatives:

rootList.add(record + "");

or

rootList.add(new String(record));

Upvotes: 0

Related Questions