2015-02-09 79 views
0

使用ConcurrentHashMap和androids parcel机制时遇到了一些奇怪的行为。尝试拆开ConcurrentHashMap时出现ClassCastException

我的情况是,我有一个ConcurrentHashMap,它在某个点上是分组的。

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异常发生在我被它序列化到一个包,然后写捆包裹做到这一点的推荐方式尝试将检索到的地图转换回ConcurrentHashMap时的最后一行。 由于HashMap和ConcurrentHashMap都实现了Serializable接口并且扩展了AbstractMap我不太了解这个问题。

有人也经历过这种情况,或者可以解释这个问题吗?

+1

你的自定义类还应该实现可串行化接口 – 2015-02-09 11:29:10

+0

自定义类实现了Parcelable。我忘了提及的是,如果我将concurrentMap的类型更改为HashMap,它就可以工作。 – JimmyVanBraun 2015-02-09 11:37:02

回答

1

好吧,所以这是没有解释,但至少有一个快速解决我的问题。我不喜欢它,但它的工作原理。由于'getSerializable()'以某种方式将我的ConcurrentHashMap视为一个普通的HashMap,我暂时使用一个HashMap来获得我的ConcurrentHashMap。

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