当前位置:   article > 正文

java类转换异常,java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long_class java.lang.integer cannot be cast to class ja

class java.lang.integer cannot be cast to class java.lang.long (java.lang.in

博客来源:

进行类转换的时候,Integer转换为long是出错

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.demo, PID: 13621
    java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
        at com.example.demo.MainActivity$4.onClick(MainActivity.java:76)
        at android.view.View.performClick(View.java:5616)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
        at android.view.View$PerformClick.run(View.java:22292)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

我的测试代码为

  1. Map<String,Integer> map = new HashMap<>();
  2. map.put("data",1);
  3. Integer dd = map.get("data");
  4. long data = map.get("data");
  5. Long data1 = (long) map.get("data");
  6. System.out.println(data);
  7. System.out.println(data1);
  8. System.out.println((data1==data));
  9. Map<String,Object> map1 = new HashMap<>();
  10. map1.put("data",dd);
  11. System.out.println(map1.get("data"));
  12. //正确转换的代码
  13. long l = Long.parseLong(map1.get("data").toString());
  14. //转换会报错的代码
  15. long l = (long)map1.get("data");
  16. System.out.println(l);

 有此代码测试可见,Integer转long显示转换是可以的,当为隐式转换时就会出错

long l = Long.parseLong(map1.get("data").toString());//转换为String后再转为Long

 

 

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/604660
推荐阅读
相关标签
  

闽ICP备14008679号