在 Java 中 java.lang.Long 不能转换为 java.lang.String

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31066811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:36:07  来源:igfitidea点击:

java.lang.Long cannot be cast to java.lang.String in Java

javacasting

提问by Syed

I'm getting response in this manner:

我以这种方式得到回应:

[{Id=1066276530, Key1=1815401000238}, {Id=1059632250, Key1=1815401000244}]

When I iterate and convert the values into a string, it throws me the error:

当我迭代并将值转换为字符串时,它会抛出错误:

java.lang.Long cannot be cast to java.lang.String in Java

 for (Map<String, String> map : leadIds) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String applicationNumber = (String) entry.getValue();
        }
}

I want to convert the value into a string. Is there any issue here?

我想将值转换为字符串。这里有什么问题吗?

采纳答案by codeaholicguy

Use String.valueOf()instead of casting:

使用String.valueOf()代替铸造:

for (Map<String, Long> map : leadIds) {
        for (Map.Entry<String, Long> entry : map.entrySet()) {
            String applicationNumber = String.valueOf(entry.getValue());
        }
}

回答by Igor Patsian

Because Stringand Longare completely different types you cannot cast them, but you can use static method String.valueOf(Long value)and backwards Long.valueOf(String value).

因为StringandLong是完全不同的类型,你不能强制转换它们,但你可以使用 static methodString.valueOf(Long value)和向后Long.valueOf(String value)