TreeMap ClassCastException

时间:2018-04-25 15:38:49

标签: java generics gson classcastexception treemap

无法找出导致此ClassCastException的String转换的来源。我已经清除了地图,只留下一个条目(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 class

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)

1 个答案:

答案 0 :(得分:0)

问题是ScoreRecord.scoreMap.getClass()的结果是一个Java类,它不包含与泛型有关的信息。在您的具体情况下,它只是SortedMap,相当于SortedMap<Object, Object>而不是SortedMap<Integer, Integer>

你需要做的是创建Gson所谓的“类型令牌”。这将为Gson提供必要的提示,以便能够成功解析您的收藏:

private void populateScoreMap(String toConvert)
{
    Gson gson = new GsonBuilder().create();
    Type collectionType = new TypeToken<SortedMap<Integer, Integer>>(){}.getType();

    ScoreRecord.scoreMap = gson.fromJson(toConvert, collectionType);
}

Gson的documentation

也解释了这一点