简体   繁体   中英

Java foreach loop unnecessary float to int casting

Vector<Vector<Integer>> wavesInformation;

for(Vector<Integer> waveInformation : wavesInformation) {

    for(Integer enemyIndex : waveInformation) { 

    }

}

Gives run time error:

Exception in thread "LWJGL Application" java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer

In for(Integer enemyIndex : waveInformation) { line.

Thats rather confusing, because no float is used.

Writing

for(Float enemyIndex : waveInformation) {   

Gives compilation error:

Type mismatch: cannot convert from element type Integer to Float

EDIT:

I look up wavesInformation in debug mode, and discovered that stored numbers are really floats (0.0) .

EDIT2:

Well, that is really strange.

For experimentation purposes I changed for loop to:

for(int i = 0 ; i < waveInformation.size() ; i++) {

I tried to assing a value from waveInformation to a variable like this:

float x = waveInformation.get(i);

and:

int x = waveInformation.get(i);

I've got the same error.

SOLUTION:

The problem was with Json parser (libgdx). I have read that libgdx json has limited support with nested generics and it only supports the first level. Eg, with ArrayList<Integer> it works, and values are read as Integers (but json.setElementType(Mission.class, "wavesInformation", Integer.class); line must appear (LIBGDX JSON specific). ArrayList<ArrayList<Integer>> will not work for now.

The solution is to add java.lang.Integer, before any number of that type in json file. Also for substitute - Gson (Google Json parser) supports nested generics. Other solution is more complicated and needs writing custom serialization method ( read more ).

Because I want to use libgdx json parser for now I have changed to `List>' and I'm casting each value to Integer (temporary solution).

You 1 have most likely ignored or suppressed some compiler warnings about unsafe casting, and your Vector<Integer> really contains some Float objects. Code that uses generics is not guaranteed to be statically type-safe if you ignore those warnings.


1 - In this case, it was a library that you are using that did this ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM