This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
No, you can't use generics to avoid that cast, because ObjectInputStream is not a generic class.
There's a good reason why it's not a generic class - a stream can contain (and usually does) many different kinds of objects, it wouldn't be very useful to have an ObjectInputStream that could read only one kind of object.
The ObjectInputStream and OutputStream are used to read and write any type of object. When you are trying to readObject from the Stream it will return you the Object type and we have to type cast.
But we can't provide the generic to this one , and the reason is , it reads or writes any type of object. So we dont know which is next object. Just we have to check with type cast and it is safe too.
More inputs are welcome.
Joined: Jan 20, 2005
Yes I have also think that reason. but if Collection can use the Genrics . why can't this ObjectOutputStream and ObjectInputStream . Even Collection also can written in to the File. Which can contain the list of many type of Objects.
Originally posted by Arul Prasad: Yes I have also think that reason. but if Collection can use the Genrics . why can't this ObjectOutputStream and ObjectInputStream .
It could, but it would be of much less value.
When you have a List<Animal>, the compiler makes sure that only Animals are put into the list. So if you get an object from the list, you can be very sure that it *must* be an Animal.
When you have an ObjectInputStream<Animal>, the input is just a binary stream. The compiler can't guarantee that the stream was produced using an ObjectOutputStream<Animal>, so we actually don't know what the stream actually contains.
So, for a list, if you use generics consequently, you can be quite sure that you will never get a ClassCastException - the compiler would already find out about the problem. That's simply not possible for the streams, because you use two different objects to write and read the stream.
Does that sound reasonable?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus