May be this is very simple but I am struggling a lot from hours. I have a list of Long which has got some 100 values in it. I have to loop through this list and have to get the value at ith position in a Long variable.
List<Long> dmrIds = (List<Long>)q.getResultList();
is my list which is fetching data from DB. I am using a for loop
for(int i=0;i<dmrIds.size();i++){
Long dmrId = dmrIds.get(i).longValue();
..........
}
When I try to convert into Long, it is giving:
`java.math.bigDecimal` can't be converted into `java.lang.Long`
I am unable to crack it. Please help.
Even though you're casting the result of q.getResultList()
to a List<Long>
, that cast doesn't really check that it's a List<Long>
... because at execution time, it's really just a List
. (This is due to type erasure in Java generics.)
It sounds like really it's a List<BigDecimal>
... so either you need to change what getResultList()
does, or you need to handle the fact that it's a List<BigDecimal>
and deal with the BigDecimal
values.
You can validate this by iterating over each element and just printing out the type:
List<?> results = (List<?>) q.getResultList();
for (Object result : results) {
System.out.println(result.getClass());
}
Or look at it in a debugger, of course.
To get all the values as long
, you just need to call longValue()
:
List<BigDecimal> results = (List<BigDecimal>) q.getResultList();
for (int i = 0; i < results.size(); i++) {
long result = results.get(i).longValue();
// ...
}
(If you don't actually need the index, I'd suggest using an enhanced for loop instead of explicitly getting each item by index though.)
See more on this question at Stackoverflow