java.math.BigInteger cannot be cast to java.lang.Integer

后端 未结 5 1843
予麋鹿
予麋鹿 2020-12-13 09:48

I\'m getting the following exception.

Caused by:

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer

相关标签:
5条回答
  • 2020-12-13 10:32

    You can try this:

    ((BigDecimal) volume).intValue();
    

    I use java.math.BigDecimal convert to int (primitive type).

    It is worked for me.

    0 讨论(0)
  • 2020-12-13 10:39

    The column in the database is probably a DECIMAL. You should process it as a BigInteger, not an Integer, otherwise you are losing digits. Or else change the column to int.

    0 讨论(0)
  • 2020-12-13 10:40

    java.lang.Integer is not a super class of BigInteger. Both BigInteger and Integer do inherit from java.lang.Number, so you could cast to a java.lang.Number.

    See the java docs http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Number.html

    0 讨论(0)
  • 2020-12-13 10:45

    You can use:

    Integer grandChildCount = ((BigInteger) result[1]).intValue();
    

    Or perhaps cast to Number to cover both Integer and BigInteger values.

    0 讨论(0)
  • 2020-12-13 10:47

    As we see from the javaDoc, BigInteger is not a subclass of Integer:

    java.lang.Object                      java.lang.Object
       java.lang.Number                       java.lang.Number
          java.math.BigInteger                    java.lang.Integer
    

    And that's the reason why casting from BigInteger to Integer is impossible.

    Casting of java primitives will do some conversion (like casting from double to int) while casting of types will never transform classes.

    0 讨论(0)
提交回复
热议问题