When using an android bundle, why does a serialised stack deserialise as an ArrayList?

后端 未结 3 932
醉酒成梦
醉酒成梦 2020-12-31 12:02

Serialisation:

Bundle activityArguments = new Bundle();
Stack> wizardSteps = new Stack

        
相关标签:
3条回答
  • 2020-12-31 12:46

    I hope am not talking any nonsense!

    Stack does not implement Serializable but rather just extends the Serializable Vector which is equivalent to ArrayList

    I am unaware of the real definition of equivalent and how loose could that be, but it is sufficient to say that the first super class of Stack that is Serializable is Vector.

    Since we see this exception, then I would probably assume that casting the Serializable to ArrayList should not throw this exception. Otherwise, I am talking nonsense.

    0 讨论(0)
  • 2020-12-31 12:49

    Just cast the serializable you retrieved from the bundle to a List, create a new Stack, and then add all the List items to the stack:

    Serializable serializable = savedInstanceState.getSerializable("key");
    List<Something> list = (List<Something>) serializable;
    Stack<Something> stack = new Stack<Something>();
    stack.addAll(list);
    

    Why cast to List and not ArrayList you ask? Because if this is fixed in some Android version, you won't have a ClassCastException again.

    0 讨论(0)
  • 2020-12-31 12:55

    Its known bug. I surprise that it still exists.

    Use generic container like:

    public class SerializableHolder implements Serializable {
    private Serializable content;
    public Serializable get() {
        return content;
    }
    public SerializableHolder(Serializable content) {
        this.content = content;
     }
    }
    

    If you use GSON library, convert your Stack to String and use as single String for Bundle without Serialize. It should work.

    0 讨论(0)
提交回复
热议问题