我正在从 mongo 光标对象中提取一个 int,如下所示:
DBObject mapObj = cursor.next();
int autostart = (int) (double) (Double) mapObj.get("autostart");
我必须三次转换才能将其变为整数似乎很奇怪,有没有更好的方法?
我认为你真正想要的是这样的:
DBObject mapObj = cursor.next();
int autostart = ((Number) mapObj.get("autostart")).intValue();
不转换为字符串,如果该值从原始 Integer 值转换为 Double 或 Long(可能会丢失精度),则它是安全的。Double、Long 和 Integer 都扩展了 Number。
HTH 罗布
Also, you can do it this way:
int autostart = Integer.valueOf(mapObj.get("autostart").toString());
Regarding your last comment:
If you want double, use this:
int autostart = Double.valueOf(mapObj.get("autostart").toString());
But what is the sense in that? You could rather have :
double autostart = Double.valueOf(mapObj.get("autostart").toString());
是的,你只需要一个演员表。
double autostart = (Double) mapObj.get("autostart");