【发布时间】:2014-07-22 14:31:51
【问题描述】:
Vector<Vector<Integer>> wavesInformation;
for(Vector<Integer> waveInformation : wavesInformation) {
for(Integer enemyIndex : waveInformation) {
}
}
给出运行时错误:
Exception in thread "LWJGL Application" java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
在for(Integer enemyIndex : waveInformation) { 行。
这很令人困惑,因为没有使用浮点数。
写作
for(Float enemyIndex : waveInformation) {
给出编译错误:
Type mismatch: cannot convert from element type Integer to Float
编辑:
我在调试模式下查找wavesInformation,发现存储的数字确实是浮点数(0.0)。
EDIT2:
嗯,这真的很奇怪。
出于实验目的,我将 for 循环更改为:
for(int i = 0 ; i < waveInformation.size() ; i++) {
我尝试将 waveInformation 中的值赋值给如下变量:
float x = waveInformation.get(i);
和:
int x = waveInformation.get(i);
我遇到了同样的错误。
解决方案:
问题出在 Json 解析器 (libgdx) 上。我读过 libgdx json 对嵌套泛型的支持有限,它只支持第一级。例如,ArrayList<Integer> 可以工作,并且值被读取为整数(但必须出现json.setElementType(Mission.class, "wavesInformation", Integer.class); 行(LIBGDX JSON 特定)。ArrayList<ArrayList<Integer>> 暂时不起作用。
解决方案是在 json 文件中该类型的任意数量之前添加java.lang.Integer,。
也可以替代 - Gson(Google Json 解析器)支持嵌套泛型。其他方案比较复杂,需要编写自定义序列化方法(read more)。
因为我现在想使用 libgdx json 解析器,所以我已更改为 `List>' 并将每个值转换为 Integer(临时解决方案)。
【问题讨论】:
-
为什么使用 Vector?你很可能想使用 java.util.List
-
看看这个stackoverflow.com/questions/1386275/… 因为@AdriaanKoster 是对的。向量已弃用
-
很高兴知道,谢谢。我已经按照你的建议做了,但是使用 java.util.List 并没有解决我的问题。
-
这就是我发表评论而不是答案的原因。
标签: java json vector foreach libgdx