37

I'm getting the following exception.

Caused by:

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

with the following code

List queryResult = query.list();

for (Iterator<Object[]> it = queryResult.iterator(); it.hasNext();) {
    Object[] result = it.next();
    Integer childId = (Integer) result[0];
    Integer grandChildCount = (Integer) result[1];
    CompanyNode childNode = childNodes.get(childId);
    childNode.setHasChildren(grandChildCount != 0);
    childNode.setIsLeaf(grandChildCount == 0);
}

at this line

Integer grandChildCount = (Integer) result[1];

Does anybody have any idea?

1
  • Thanks everyone, I'm trying it out now in production, hopefully it works now. Mar 1, 2012 at 5:34

5 Answers 5

71

You can use:

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

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

0
19

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.

1
  • I was confused because the local database was generated with an Integer by hibernate and the same should of happened with production, but it was changed to an int in production. Mar 1, 2012 at 5:53
5

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

5

You can try this:

((BigDecimal) volume).intValue();

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

It is worked for me.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.