【发布时间】:2018-04-25 15:38:48
【问题描述】:
无法确定导致此 ClassCastException 的字符串转换来自何处。我已经清除了地图,以便它只包含一个条目 (115,1563),并且我确保两个参数都是整数。
首先我从一个文件中读取并填充 scoreMap。
private void populateScoreMap(String toConvert)
{
Gson gson = new GsonBuilder().create();
ScoreRecord.scoreMap = (TreeMap<Integer,Integer>) gson.fromJson(toConvert, ScoreRecord.scoreMap.getClass());
}
ScoreRecord 类
public class ScoreRecord
{
public static SortedMap<Integer,Integer> scoreMap = new TreeMap<Integer, Integer>();
}
然后我尝试在 ScoreGraph 类中添加一个条目
private void addTodaysScore() {
Integer todaysScore = getIntent().getIntExtra("score",0);
Calendar calendar = Calendar.getInstance();
Integer dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
ScoreRecord.scoreMap.put(dayOfYear,todaysScore);
}
例外
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Integer.java:1044)
at java.util.TreeMap.put(TreeMap.java:593)
at com.xxx.xxx.xxx.xxx.ScoreGraph.addTodaysScore(ScoreGraph.java:63)
【问题讨论】:
-
你能转储 scoreMap 中的所有键吗?它在
compareTo内部失败,如果地图中已经有一个 String 键,就会出现这种情况。 -
哦,这可能吗?即使 scoreMap 的类型被定义为使用整数键和值?...不认为这是可能的,我将查看地图中的数据。
-
你能分享你这个类的完整代码吗?
-
绝对有可能——请记住,泛型仅用于编译器的类型检查,而底层类型只是
Object。检查可以很容易地被强制转换覆盖,注意这样的代码:((SortedMap)scoreMap).put("hello", "world");ideone.com/CF9lAB -
getIntent().getIntExtra("score",0) 也共享这些方法。
标签: java generics gson classcastexception treemap