Help Needed: Serialization Problem

I've got a problem with serialization, which is better illustrated with an example (slightly modified version of example in Tech Tips, February 29, 2000, Serialization in the Real World. The problem is that comparing serialized static final fields doesn't return correct result. Any help on how to fix this problem would be greatly appreciated. Thanks in advance. Here is the code:
====================
import java.io.*;
class Gender implements Serializable {
String val;
private Gender(String v) {
val = v;
public static final Gender male = new Gender("male");
public static final Gender female = new Gender("female");
public String toString() {
return val;
public class Person implements Serializable {
public String firstName;
public String lastName;
private String password;
transient Thread worker;
public Gender gender;
public Person(String firstName,
String lastName,
String password,
Gender gender) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.gender = gender;
public boolean isMale() {
return gender == Gender.male;
public boolean isFemale() {
return gender == Gender.female;
public String toString() {
return new String(firstName + " " + lastName);
public static void main(String [] args) {
Person p = new Person("Fred", "Wesley", "cantguessthis", Gender.male);
//-NOTE: there ia no problem with this check
if (p.isMale()) {
System.out.println("a male: " + p);
} else if (p.isFemale()) {
System.out.println("a female: " + p);
} else System.out.println("strange");
class WritePerson {
public static void main(String [] args) {
Person p = new Person("Fred", "Wesley", "cantguessthis", Gender.male);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream(
"Person.ser"));
oos.writeObject(p);
catch (Exception e) {
e.printStackTrace();
finally {
if (oos != null) {
try {oos.flush();}
catch (IOException ioe) {}
try {oos.close();}
catch (IOException ioe) {}
class ReadPerson {
public static void main(String [] args) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(
new FileInputStream(
"Person.ser"));
Person p = (Person)ois.readObject();
//-NOTE: this is the problem: the check returns false
if (p.isMale()) {
System.out.println("a male: " + p);
} else if (p.isFemale()) {
System.out.println("a female " + p);
} else System.out.println("strange");
catch (Exception e) {
e.printStackTrace();
finally {
if (ois != null) {
try {ois.close();}
catch (IOException ioe) {}
}

The Gender class implements a type-safe enumeration, but its implementation needs to be improved to ensure that re-creating a Gender object via deserialization doesn't create new objects but uses the existing objects. See this article for details on how that's done:
http://developer.java.sun.com/developer/Books/shiftintojava/page1.html

Similar Messages

  • Help neede urgently(Problem in adding exponential numbers)

    Hi,
    Actually i want to add the contents of two files which contains exponential numbers.
    i'm not able to add these numbers. Can any one help me?
    import java.io.*;
    import java.nio.*;
    class  userFile
         public static void main(String[] args) throws IOException
              try
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
              String s1,s2,s3;
              FileReader fr1,fr2;
              System.out.println("Enter first file :");
              s1=br.readLine();
              System.out.println("Enter second file :");
              s2=br.readLine();
              System.out.println("Enter new file :");
              s3=br.readLine();
              fr1= new FileReader(s1);
              fr2= new FileReader(s2);
              BufferedReader fin1=new BufferedReader(fr1);
              BufferedReader fin2=new BufferedReader(fr2);
              String str1,str2,str3;
              double i1,i2,i3;
              OutputStream fout=new FileOutputStream(s3);
              while((str1=fin1.readLine()) != null)
                   while((str2=fin2.readLine()) != null)
                   i1=Float.parseFloat(str1);
                   System.out.println(i1);
                   i2=Float.parseFloat(str2);
                   System.out.println(i2);
                   i3=i1+i2;
                   System.out.println("i3=" +i3);
                   str3 = Float.toString(i3);
                   byte buf[]=str3.getBytes();
                   fout.write(buf);
                   fout.write('\n');
              catch(NumberFormatException e)
                   System.out.println(e);
    }I need help urgently.
    Thanks in advance.

    By "exponential number, do you mean one in scientific notation (eg. -1.55743e21) or what?
    What do your files look like?
    What problem are you encountering? Is an exception being thrown? If so, give us the exact message (copy/paste). Is the results simply not what was expected? If so, give us the input, the expected results and the actual results for us to compare and consider.
    Chuck

  • Help needed - DEP problem

    Hi.
    I need help with the installation of Flash Player ActiveX.
    I have Win 7 Home Premium Edition, 64 Bit.
    Everything worked perfectly on my laptop, and I could saw flash objects both on the 32bit explorer and the 64bit explorer version.
    Until recently I've clicked on the 'Restore Default' button in the Explorer menu.
    Since then - when I try to broswe with the 32bit Explorer edition - I keep getting messages like the following:
    "Internet Explorer has stopped working"
    And then - "
    Windows Data Execution Prevention detected an add-on trying to use system memory incorrectly. This can be caused by a malfunction or a malicious add-on.
    Other things you can do:
    Go online to learn about the Data Execution Prevention (DEP) security feature"
    When I disable the "Shockwave Flash Object" from the adds-on menu - everything's good, just I can't see the flash objects, of course.
    I'm tring to install the Flash Player ver. 10.2.159.1 through the DLM or through the manual installation - each time leading to the same result - "Internet Explorer has stopped working".
    With the 64bit Explorer edition - I get no error message - but no flash displayed as well.
    Any help will be much appriciate.

    Ok, I tried to lower it to the minimum - problem still exist.
    And of course I've uninstalled it before. I know a little about computers, just not enough, apparently..
    Keep on trying!
    (Oh, BTW - I've successfully installed flash on the 64Bit version of explorer. ver. 13 something... is there is something like this?
    Anyway, now I need my 32bit version to work...)
    TY.

  • Help needed, possible problem with HDD

    In the last few weeks, my iMac has become quite slow and tends to freeze fairly often. The other day I turned it on and was met with a kernel panic screen and could not access my desktop or any of my files. To find the source of the problem I ran an Apple Hardware Test which gave me the following error:
    4HDD/11/40000004:SATA (0,0)
    After searching on the internet, I decided to boot from my OSX install disc and run Disk Utility. After verifying the disc, and repairing the disc, the scan revealed that there was no problem with the HDD. However, I was still being met with the kernel panic screen whenever I tried to turn on the computer.
    After booting from the install disc again, I did an Archive and Install, which finally let me get to my desktop, however the computer was once again running slowly and after another Apple Hardware Test it resulted in the same error as above.
    After more searching on the internet, I decided to remove the 3rd party RAM from my iMac and replace it with the original RAM. No success again.
    More searching brought Disk Warrior to my attention. After purchasing the program, I ran the included scans and once again was given the result that there was nothing wrong with the HDD.
    After this I decided to run Tech Tools Deluxe which came up with a Directory fail, even though the Disk Utility and Disk Warrior scans found no such problem.
    So what procedure can I take now, I am hesitant to perform a System Restore as I do not want to lose my files, but this may be my only option.
    Please help.

    Okay, I ended up installing OSX to my external HD and booted from that. Ran Disk Warrior from the external and used it to rebuild the internal HD. After the rebuild DW gave me the message that it could not replace the new directory with the old directory as there was a disk malfunction. I managed to copy all of my important data to the external.
    I'm guessing that the internal needs to be replaced? I'd rather start fresh with a new one than risk this happening again anyways.
    In any case thank you very much for your help, it was much appreciated .

  • Urgent deadline - Please help - Linux serialization problem

    Hi -
    I have a presentation on Wednesday morning of my program for my dissertation. I developed the whole thing in windows - it all works great... but the demo is on a Linux machine. Fortunately I tested today in Linux. I have a real problem. I want to save out a class instance. This code works fine in Windows:
                        String project_name = f.getAbsolutePath() + "/" + directory_name + ".oll";
                        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(project_name));
                        out.writeObject(mainCanvas);
                        out.flush();
                        out.close();The problem is that in Linux I just don't get anything saved. There is nothing there at all. No file is saved. I cannot work this out and am in a panic. Any help really appreciated.
    Olly

    Hi ,
    Please try to add this code to u'r prg.
    private void writeFile(String s, String s1)
    throws IOException
    Object obj = null;
    FileWriter filewriter = null;
    BufferedWriter bufferedwriter = null;
    if(sfmsDebug)
    System.out.println("Before Writing Received Messages To a File.");
    String s2 = System.getProperty("file.separator");
    if(System.getProperty("os.name").toUpperCase().indexOf("WIN") !=
    -1)
    File file = new File("c:" + s2 + s1);
    boolean flag = file.createNewFile();
    filewriter = new FileWriter("c:" + s2 + s1, true);
    bufferedwriter = new BufferedWriter(filewriter);
    } else
    File file1 = new File("/home/usr2/barcwas1" + s2 + s1);
    boolean flag1 = file1.createNewFile();
    filewriter = new FileWriter("/home/usr2/barcwas1" + s2 + s1, true);
    bufferedwriter = new BufferedWriter(filewriter);
    bufferedwriter.write(s, 0, s.length());
    bufferedwriter.write("\r\n");
    bufferedwriter.close();
    filewriter.close();
    if(sfmsDebug)
    System.out.println("After Writing Received Messages To a File.");
    }

  • [HELP NEEDED] FBN1 Problem

    Hello SAP Masters,
    We have a problem with FBN1.
    The current document number that was recorded there was: XXXXXX59
    However, when we checked, the last posted document was: XXXXXX60.
    Therefore when we try to post a new document, the system tries to save XXXXXX60 since the last document number that was recorded in FBN1 is XXXXXX59. But since document XXXXXX60 already exists we can not save any more doc.
    Do you have any idea why this happened or What may be the solution for this?
    Thanks so much for your help!
    Regards

    Hello
    Try this one
    Change the number range from 61 to xxxxxx for the number range number and ty posting a document.
    Hope this should solve ur problem
    Thanks
    sanjeev

  • Help Needed.Battery problem

    Hello,
    I desperately need help for my iphone.Sometimes iphone shows that battery is empty.The battery's life is fine but sometimes when i press the power or home button so that iphone comes out of stand by it shows no battery, if i try again after a while battery is fine.Please help because i lose some calls or sms's because of this.

    Reboot the phone now and then (just good practice)
    To Reboot. Press and hold both the Lock and Home buttons. Do not let go when it says Slide to Turn Off. Keep holding until you see the Apple Logo, then you can let go. This is a full reboot of the OS. No data will be lost. Takes about 10seconds of button holding and maybe 30secs to min to reboot.

  • [help needed] Javadoc problem with many files

    Hi,
    I have an Ant script generating my javadoc every night. I have about 5700 java files making about 42MB of data.
    It worked fine for two years until two weeks ago, where the script stopped with the following message :
    <<
    [... big snip...]
    [javadoc] C:\Temp\Java\blablabla.java:58: cannot resolve symbol
    [...snip...]
    [javadoc] public HtmlComponent getCell(
    [javadoc] ^
    [javadoc] 100 errors
    [javadoc] 1 warning
    BUILD SUCCESSFUL
    Total time: 1 minute 40 seconds
    >>
    If I execute the javadoc generation on a smaller set of java source files, I still have a lot (100 displayed) of error messages like the one above (which generaly don't stop javadoc), but the generation continues :
    <<
    [...big snip...]
    [javadoc] C:\Temp\Java\xxx.java:12: cannot resolve symbol
    [...snip...]
    [javadoc] public SelectionNoop(Fig fig) {
    [javadoc] ^
    [javadoc] Standard Doclet version 1.4.2_08
    [javadoc] Generating C:\temp\JavadocNewSI\constant-values.html...
    [javadoc] Building tree for all the packages and classes...
    [javadoc] Generating C:\temp\JavadocNewSI\com\zz\common\job\common\class-use\ManagerDelegate.html...
    [...big snip...]
    [javadoc] Generating C:\temp\JavadocNewSI\stylesheet.css...
    [javadoc] 6251 warnings
    BUILD SUCCESSFUL
    Total time: 23 minutes 33 seconds
    >>
    I don't understand what's going on. It is not a memory problem since it issues an intelligible message.
    I also managed to generate javadoc for several subsets, so it can't be a problem with one file or folder crashing javadoc.
    Any help welcome,
    Tug

    Well, it seems that the cause was indeed an empty java file...
    The generation fails if the empty java file is the set AND a refering file is in the set. If only one of these conditions are missing, then javadoc goes on...
    What I don't understand is that the empty file used to be here since may 2005 and the referring class is unchanged since 2004... it never bugged javadoc before.
    Creepy...
    Tug

  • Ichat Help Needed: Connection Problem

    I purchased a new imac about 2 months ago. I have been having problems with my ichat ever since the beginning. When ever I open my ichat to login it says: Lost connection with AIM, the connection to the host was unexpectedly lost, Almost immediately upon login. I have never infact been able to access ichat because I can never login. My internet connection is fine, I have been using the internet with no problems what so ever. I have been using AIM express in the time being and it has worked fine. I have tried updating my software and creating a new AIM screen name but it hasent helped. I would greatly appreciate if someone could tell me how to solve this problem.
    Thank You.
    iMac Mac OS X (10.4.10)

    hi Olivier,
    In that case do two things
    1) Download and Instll the Combo version of the Update
    See this list http://www.apple.com/downloads/macosx/apple/macosx_updates/
    2) reboot the Modem and or router.
    1:35 PM Wednesday; July 11, 2007

  • Urgent Help Needed: Installation problem on Win2K

    My j2sdk1.4.1_01 folder got deleted, I tried to reinstall J2SDK1.4.1_01 but everytime I try I get a dialog box that pops-up saying:
    You already have the Java 2 SDK , SE v1.4.1_01installed on this machine. Would you like to uninstall it?
    Clicking OK runs a very brief uninstall, but apparently doesn't actually uninstall, Win Add/Remove Programs does the same thing, it runs, says it uninstalled it, but doesn't. Anyone have any ideas?

    Same problem here. The installer crashed at the very end of the installer procedure, so I attempted to uninstall. I failed, so I manually deleted files and attempted to reinstall.
    The system claims that the software is still installed and when I instruct it to uninstall, it immediately terminates.
    I've even deleted the HKLM\SOFTWARE\JavaSoft\Java Development Kit\1.4.1_01 key. The installer puts it back when you tell it to uninstall the software!!
    Anyway, the work around is to go into RegEdit and delete the two keys that contain mention of version 1.4.1_01. There are two, one in
    HKLM\SOFTWARE\Microsoft\Code Store Database\Distribution Units
    and the other in
    HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
    Both has long hexadecimal string names (CSIDs?)
    I was then able to reinstall...

  • Help needed. Problem with servlet.

    Hello ppl. Ok. I've never really needed to implement servlets in my projects before but I experimented by writing a simple helloworld servlet. It compiled successfully and I tested it in the examples servlet dir and it worked. To test it in the ROOT dir, I placed the servlet in the ROOT/WEB-INF/classes folder and edited the web.xml file with:
    <servlet>
              <servlet-name>HelloWorldExample</servlet-name>
              <servlet-class>HelloWorldExample</servlet-class>
         </servlet>
         <servlet-mapping>
              <servlet-name>HelloWorldExample</servlet-name>
              <url-pattern>servlet/*</url-pattern>
         </servlet-mapping>
    When I try and execute the servlet by using this URL: localhost:8080/servlet/helloworld I get an internal server error and the server crashes. I removed the entry from the web.xml file and Tomcat started up again. What went wrong? Can someone enlighten me in how to get my test servlet working becuase i may use them in the future. Thanks.

    Nope, Still didnt work. As soon as I put in:
    <servlet>
         <servlet-name>HelloWorldExample</servlet-name>
         <servlet-class>HelloWorldExample</servlet-class>
         </servlet>
         <servlet-mapping>
         <servlet-name>HelloWorldExample</servlet-name>
         <url-pattern>servlet/HelloWorldExample</url-pattern>
         </servlet-mapping>
    Tomcat went offline!
    I have another entry which is:
    <servlet>
              <servlet-name>org.apache.jsp.index_jsp</servlet-name>
              <servlet-class>org.apache.jsp.index_jsp</servlet-clas
    >
         </servlet>
         <servlet-mapping>
              <servlet-name>org.apache.jsp.index_jsp</servlet-name>
              <url-pattern>/index.jsp</url-pattern>
         </servlet-mapping>
    Do you think they may be conflicting? Thanks.Tomcat going offline is quite weird. However,
    <url-pattern>/index.jsp</url-pattern>
    this is perfectly valid. Lemme ask you this: did u come up with this stuff on your own or was it generated for you by the container? It looks like it was generated upon compilation of the jsp. If that is the case it should cause any conflicts. However now if you want to invoke the servlet/jsp you must use a URL like:
    http://localhost:<PORT_NO>/index.jsp
    Cheers

  • URGENT HELP NEEDED: Sorting problems

    I am trying to sort large document of around 1,000,000 records into file but I can't do it.
    I receive the following message:
    Cputime limit exceeded
    52.760u 8.240s 1:46.94 57.0% 0+0k 0+0io 2098pf+0w
    Is this fixable? Do you know what's the cause of the problem?

    There should be a limit placed by UNIX systems administrator.
    Is there any other way? I looked in the man pages for some way of setting and changing the resource limits from the command line, but couldn't find anything. Perhaps someone who understands *nix better might know.
    java -Xmx10m ...This switch sets memory rather than cpu time.
    How long is the sort taking any way?

  • Help needed, authorization problems

    When I buy songs from Itunes I'm asked to authorize my PC. Although I then get the message, that authorization was successful (1 of 5 PCs), I cannot play the song and again and again the authorization field pops up, it's like a loop. I have no idea what to do anymore.

    Scroll down to the "Remove the SC Info folder" section of this article and see if it helps...
    iTunes repeatedly prompts to authorize computer to play iTunes Store purchases
    http://docs.info.apple.com/article.html?artnum=306424
    Cheers,
    Patrick

  • Help needed in problem in Installation

    Dear Oracle Guys,
    When i install Oracle developer6 iam getting the following error :
    user.avf(44):unbound variable 'w32rsf80'
    and the installer quits.I tried clearing all the entries in registry(windows NT) and tried again and i got the same error.
    I would like to know what this error means and what is the solution.
    Thanx in advance,
    Alfred

    here is my menu list http://pastebin.com/FdAiHnXZ
    and the errors

  • Help needed, M getting this message sandbox environment error no test user account, when downloading any application from iTunes, friend told me to sign out and sign in iTunes it might solve the problem but instead I cannot login I to my itune account.

    Help needed,
    I am getting this message sandbox environment error no test user account, when downloading any application from iTunes, friend told me to sign out and sign in iTunes it might solve the problem , and i triyed it but still  I cannot login I to my itune account. Same message keeping. Popping up,  this problem started supricly today.

    Take a look at the instructions here.
    http://www.technogal.net/2012/03/this-is-not-test-user-account-please.html

Maybe you are looking for

  • Locked threads, instead of hiding "reply" link change word to "Locked"

    Based on this thread: http://social.microsoft.com/Forums/en-US/cc444c7a-a838-4a16-ac57-8f315475b602/how-does-one-reply-to-a-post-i-see-no-reply-button?forum=reportabug It seems that for locked threads, people can scroll past the the "Lock" icon too q

  • Non Clustered Indexing not working for SQL server 2005

    I have create two non clustered index on two particular tables. Now the problem is its working fine..but after restarting my server its working stop and then again I have to delete that index and recreate it.

  • Statement not reached

    Hi I need help please I have these 2 errors: Statement not reached Variable tv may not have been initialized Here my code: switch(index) TreeView test; case 0: test = treeView1; break; case 1: test = treeView2; break; case 2: test = treeView3; break;

  • J(Check)Tree Problems

    Hi, I'm using the JCheckTree from: http://www.fawcette.com/archives/premier/mgznarch/javapro/2001/01jan01/vc0101/vc0101.asp And have some problems with it, hopefull somebody can help me... (source on website) 1: In a normal JTree when you dubbleclick

  • Photoshop CS4 Extended - graphic failures

    I've made a video: http://www.youtube.com/watch?v=B2OlsxGKyRw These are my Preferences: http://img43.imageshack.us/img43/3379/voreinstellungen.png I un-installed and re-installed it. It's the newest version (11.0) My Graphic drivers are very new. My