Reputation: 195
My program has a method that fetches the count of a particular row and convert it into BigInteger:
private BigInteger getSameSatPremise(ServiceAgreement sa) {
BigInteger count = BigInteger.ZERO;
StringBuffer queryHql = new StringBuffer();
queryHql.append("from Table t1");
Query query = createQuery(queryHql.toString());
query.addResult("count", "count(distinct t1.column1)");
if (query.listSize() > 0) {
count = (BigInteger) query.firstRow();
}
return count;
}
The casting works fine when the result from the query is 0. But I get a casting error like below when the result from the query is 2.
Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.math.BigInteger
Can anyone help.
Upvotes: 3
Views: 8260
Reputation: 2957
Long is not a subclass of BigInteger, so 'Long is NOT BigInteger'. So, your Long can not be cast to a BigInteger.
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html
Use static method of BigInteger: BigInteger.valueOf(long val);
as BigInteger.valueOf(query.firstRow())
.
And your code works in case of zero results because, you have initialized the count
with a ZERO of type BigInteger
. So, in case of zero results, your code does not get into the if statement (no casting is tried) and returns count
straight away.
You might also want to read about Upcasting and Downcasting in Java.
What is the difference between up-casting and down-casting with respect to class variable
Upvotes: 1
Reputation: 234785
Java ain't C++, you can't write your own conversion operators.
In Java you need to use explicit functions to do what you want. In your case that's the considerably more verbose
BigInteger.valueOf(query.firstRow())
Upvotes: 12
Reputation: 11251
java.lang.Long
and java.math.BigInteger
are in a different hierarchies. They cannot be castes to each other. You can create new BigInteger
by using static factory method
:
BigInteger.valueOf(yourLong);
Upvotes: 1