NOTE TO READER: Thanks to Tim’s help below, I was able to resolve the problem. The root of the problem wasn’t the ArrayList casting, but the fact that the runtime engine pointed the error to the wrong line, i.e. the one I show below where I access the list. The real error was 4 lines below that, where I made a mistake assigning an element into the element I just retrieved.
I’ve got a small Result class (at bottom of my grails controller class), and then in my code, I do
ArrayList<Result> bestResults = new ArrayList<Result>()
to help the compiler know what bestResults is (but tried other forms below). Then, I try to access this arraylist, via:
for (int r = 0; r < topSet; r++) {
Result res = bestResults[r] as Result
and, I get an “Cannot cast object … to blahblah.Result” run-time error.
I’ve tried other variations of both, namely:
ArrayList bestResults = new ArrayList()
with
Result res = (Result) bestResults[r]
or just
Result res = bestResults.get(r) as Result
and I always get the same casting error. I just can’t seem to please the Groovy “engine” / JVM! 🙂 🙁
Can you please assist?
———————– The more full code —————–
The Result class is at the bottom of my grails controller (main) class, namely:
class Result {
float factor
def results = null // NOTE: this will hold an array of float
}
Then, in the controller, I do the following, intializing bestResults to bogus values:
def results = new float[2 * deltaRange + 1] as float[] // the results array gets assigned to bestResults AFTER the error I get, so it seems non-relevant
ArrayList<Result> bestResults = new ArrayList<Result>()
Result fakeResult = new Result(factor: 100.0f, results: null)
for (int r = 0; r < 10; r++) {
bestResults.add(r,fakeResult)
}
Then, when I go to insert a real result, I run into the problem, doing:
for (int r = 0; r < 10; r++) {
Result res = bestResults.get(r) as Result
or doing
Result res = bestResults[r] as Result
or
Result res = bestResults[r]
All give the error:
Message: Cannot cast object '[F@4f5b6d' with class '[F' to class 'alwaysbetter.Result'
* After this error, I have the code that does:
bestResults[r].results = results
where results is defined as an array of floats at the top, namely:
def results = new float[2 * deltaRange + 1] as float[]
Right, the problem is the last bit of information you gave…
makes no sense in groovy, to get a float array of
2 * deltaRange + 1elements, your best bet is probably:Original answer
Is this inside Java code?
When you say “main class”, what do you mean?
How does this relate to grails?
This works in groovy:
Or, more groovily:
Edit after question update
That error message says you are trying to convert an
array of float(ie:float[]) into a Result objectThere must be something missing from the code you have posted, as if I paste it into a groovy console, it works fine
It’s a bit odd though…
You do realise you’re adding the same
Resultinstance to the List 10 times don’t you? Not 10 separate instances?