Hi guys. Hopefully this isn't a stupid typo error question, but...
I have my own object
// examp.java
class Security implements Serializable { String a, b; int a; }
..
And I have an array of instances of that object (which I'm not sure I'm
creating correctly.
Security allStocks[] = new Security[2]
I write the array like thus:
try
{
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("Securities.dat"));
out.writeObject(allStocks);
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
Then, I read it like this:
try
{
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("Securities.dat"));
allStocks = (Security) in.readObject();
in.close();
}
catch (IOException e)
{
System.out.println(e);
}
And I get "incompatible types" compile error on the line that says
allStocks = (Security) in.readObject(); ... the two lines are in two
different classes, how does it even know what type of object is being
read? I don't understand. Is it not possible to serialize and save an
array of objects?
Thanks in advance!
(Sorry about the code, it's hand-typed.)
--Uri
Vova Reznik - 22 Jun 2005 16:44 GMT
> Security allStocks[] = new Security[2]
> FileInputStream("Securities.dat"));
> allStocks = (Security) in.readObject();
[quoted text clipped - 4 lines]
> System.out.println(e);
> }
How about
allStocks = (Security[]) in.readObject();
Boudewijn Dijkstra - 22 Jun 2005 19:35 GMT
> Hi guys. Hopefully this isn't a stupid typo error question, but...
>
[quoted text clipped - 8 lines]
>
> Security allStocks[] = new Security[2]
Please separate the type and the name:
Security[] allStocks = new Security[2];
> I write the array like thus:
>
[quoted text clipped - 17 lines]
> FileInputStream("Securities.dat"));
> allStocks = (Security) in.readObject();
...because it avoids confusion in these cases.
> in.close();
> }
[quoted text clipped - 7 lines]
> different classes, how does it even know what type of object is being
> read?
Because you got the error from the compiler.
> I don't understand. Is it not possible to serialize and save an
> array of objects?
Only with compatible types.
> Thanks in advance!
Bjorn Abelli - 22 Jun 2005 23:08 GMT
"uri" wrote...
[snip]
> Security[] allStocks = new Security[2]
[snip]
> allStocks = (Security) in.readObject();
[snip]
> And I get "incompatible types" compile error on the line
> that says allStocks = (Security) in.readObject(); ...
> the two lines are in two different classes, how does it even
> know what type of object is being read?
It doesn't, but it knows the type of the variable "allStocks", which is
*not* Security, but an *array* of Security, and *that's* what the compiler
is complaining about.
// Bjorn A