[Solved] How to fix ClassCastException in enhanced for-loop? [closed]


The only way the problem can exist given the posted code, if the reported exception/line is correct, is when “Somerecords” is not really creating a List<Object[]> object – but a List containing non-Object[] elements.

One reason could be the method in question is typed to return a non-generic List, filled with double values. Java will type-accept this with a warning – eg. “uses unchecked or unsafe operations”.

That is, C<T> generic = (C)generic_or_plain is compile-time type-valid – even if the resulting code is run-time type-invalid. Similarly, C plain = (C<T>)compatible_generic_or_plain is valid code but can result in a misuse of plain.

Consider:

List<Object[]> r = new ArrayList<Object[]>();
List r2 = r; // Because generics are "imaginary" we can fake this,
             // but the compiler WILL GENERATE A WARNING at type information loss
r2.add(1.2); // Now we add a Double (to r since r2 is r)

// CC! - Have a Double where Object[] was expected
Object[] res = (Object[])r.get(0);

Another way this can be caused, with the same issue, but from the different side:

// Type-valid, but "unsafe" (and invalid)
List<Object[]> r = (List)Arrays.asList("Hello");

// CCE! - Have String, expected Object[]
Object[] res = (Object[])r.get(0);

Solution: Use generics everywhere and don’t ignore or suppress compiler warnings.

Suggestion: Include the full Exception Message in future posts, as it will show the types involved – and likely result in less close/down votes.

2

solved How to fix ClassCastException in enhanced for-loop? [closed]