【问题标题】:TreeMap ClassCastExceptionTreeMap ClassCastException
【发布时间】: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


【解决方案1】:

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

您需要做的是创建 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中也有说明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多