Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 436
Code Junkie Avatar asked Mar 01 '12 05:03

Code Junkie


People also ask

Can we convert BigInteger to integer in Java?

The java. math. BigInteger. intValue() converts this BigInteger to an integer value.

How do you cast Bigint to int?

BigInteger. intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int.

How do you do math operations with BigInteger in Java?

BigInteger class provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java. lang. Math. It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.


2 Answers

You can use:

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

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

like image 189
Ted Hopp Avatar answered Sep 26 '22 03:09

Ted Hopp


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.

like image 20
Andreas Dolk Avatar answered Sep 24 '22 03:09

Andreas Dolk