【问题标题】:ClassCastException when trying to unparcel a ConcurrentHashMap尝试解包 ConcurrentHashMap 时出现 ClassCastException
【发布时间】:2015-02-09 11:22:12
【问题描述】:

我在使用ConcurrentHashMap 和androids parcel 机制时遇到了一些奇怪的行为。

我的情况是,我有一个 ConcurrentHashMap,它在某个时候被打包。我按照推荐的方式将其序列化为 Bundle,然后将 bundle 写入包裹:

ConcurrentHashMap<String, CustomClass> concurrentMap = new ConcurrentHashMap<>();

...

@Override
public void writeToParcel ( Parcel dest, int flags ) {      
    Bundle map = new Bundle(1);
    map.putSerializable("map", concurrentMap);
    dest.writeBundle(map);
}

我稍后会这样检索它:

public void readFromParcel ( Parcel in ) {

    Bundle map = in.readBundle(CustomClass.class.getClassLoader());
    concurrentMap = (ConcurrentHashMap<String, CustomClass>) map.getSerializable("map");  
}

ClassCastException 在尝试将检索到的 Map 转换回 ConcurrentHashMap 时发生在最后一行。 由于 HashMap 和 ConcurrentHashMap 都实现了 Serializable 接口并扩展了 AbstractMap 我不太了解这个问题。

是否有人也遇到过这种情况或者可以解释一下这个问题?

【问题讨论】:

  • 你的自定义类也应该实现可序列化接口
  • 自定义类实现 Parcelable。我忘了提到的是,如果我将 concurrentMap 的类型更改为 HashMap ,它就可以正常工作。

标签: android serialization classcastexception parcelable parcel


【解决方案1】:

好的,所以这不是解释,但至少对我来说有一个快速修复。我不喜欢它,但它有效。

由于 'getSerializable()' 以某种方式将我的 ConcurrentHashMap 视为普通的 HashMap,我暂时使用 HashMap 来获取我的 ConcurrentHashMap。

 HashMap<String, CustomClass > tempMap = (HashMap<String, CustomClass >) map.getSerializable("map");
 concurrentMap = new ConcurrentHashMap<>(tempMap);

【讨论】:

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