views:

104

answers:

2

What is the best procedure for storing and retrieving, using native Java serialization, generic objects like ArrayList<String>?

Edit: To clarify. When I serialize an object of type ArrayList<String> I'd like to de-serialize to the same type of object. However, I know of no way to cast back to this generic object without causing warnings.

+4  A: 

I think I understand the question, though it could be stated less vaguely. When you deserialize, you could cast to raw ArrayList and as long as that doesn't throw a ClassCastException you know you got that part right; but if you further cast to ArrayList<String> (or List<String>), you'll get a warning that this is not safe. The collection might contain Integers and this cast alone won't catch that.

The usual best course of action is just to match your serialization and deserialization code to each other carefully, and suppress the warnings that result.

Kevin Bourrillion
+1  A: 

I think you're going to be stuck with the unsafe cast warnings here - Serialization can only deal with characteristics of the objects that end up in the actual bytecode, and (as I understand it) generics are stripped out by the compiler. The guts of the deserialization mechanism don't have any understanding of generic parameters.

Curtis