Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

Serialization of ArrayList resulting in Null Values

Thread view: 
scifluent@gmail.com - 24 Mar 2007 19:53 GMT
I am serializing an arraylist using the following code:

filename = "Data.ser";

        try
        {
            new File(filename).delete();
            OutputStream file = new FileOutputStream(filename);
            OutputStream buffer = new BufferedOutputStream(file);
            output = new ObjectOutputStream(buffer);
            output.writeObject(this.DataList);
            output.close();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }

... and when I read it back in using the code below...I get the
correct number of elements in the ArrayList but the elements are all
nulll values.  Any ideas???  (I have verified that the orginal list
has non-null element values.)  Thanks!!!!

ObjectInput input = null;
        try{
            //use buffering
            InputStream file = new FileInputStream( "Data.ser");
            InputStream buffer = new BufferedInputStream( file );
            input = new ObjectInputStream ( buffer );
            DataListPrev = (ArrayList<Float>) input.readObject();
            input.close();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex){
            ex.printStackTrace();
        }
Paul Tomblin - 24 Mar 2007 20:38 GMT
In a previous article, scifluent@gmail.com said:
>I am serializing an arraylist using the following code:

Serializing is a "shallow copy", just like cloning.  It doesn't serialize
the objects in the ArrayList, just the ArrayList itself.

Signature

Paul Tomblin <ptomblin@xcski.com> http://blog.xcski.com/
Windows gives you a nice view of clouds so you can't see any potentially
useful boot time messages.
             -- Bill Hay

Tom Hawtin - 24 Mar 2007 20:51 GMT
> In a previous article, scifluent@gmail.com said:
>> I am serializing an arraylist using the following code:
>
> Serializing is a "shallow copy", just like cloning.  It doesn't serialize
> the objects in the ArrayList, just the ArrayList itself.

No.

In fact you can implement deep cloning by using serialisation and
deserialisation.

Tom Hawitn
Tom Hawtin - 24 Mar 2007 20:47 GMT
> ... and when I read it back in using the code below...I get the
> correct number of elements in the ArrayList but the elements are all
> nulll values.  Any ideas???  (I have verified that the orginal list
> has non-null element values.)  Thanks!!!!

Serialisation of ArrayLists should work...

But you haven't given enough information to know what you are doing
wrong. Start with something simple that works, and work back to find
where your problem is introduced.

Here is some working *complete* code to start from:

import java.io.*;
import java.util.*;
class Write {
    public static void main(String[] args) throws Exception {
        List<Float> data = new ArrayList<Float>(
            Arrays.asList(1.0f, 2.0f, 3.0f)
        );
        ObjectOutputStream out = new ObjectOutputStream(
            new FileOutputStream("data.ser")
        );
        out.writeObject(data);
        out.close();
    }
}

import java.io.*;
import java.util.*;
class Read {
    public static void main(String[] args) throws Exception {
        ObjectInputStream in = new ObjectInputStream(
            new FileInputStream("data.ser")
        );
        List<Float> data = (List<Float>)in.readObject();
        System.out.println(data);
    }
}

Tom Hawtin
scifluent@gmail.com - 24 Mar 2007 20:52 GMT
Looks like the elementdata of an Arraylist is defined as transient for
the default writeobject().

http://www.oreilly.com/catalog/javarmi/chapter/ch10.html
Tom Hawtin - 24 Mar 2007 21:34 GMT
> Looks like the elementdata of an Arraylist is defined as transient for
> the default writeobject().
>
> http://www.oreilly.com/catalog/javarmi/chapter/ch10.html

The field is transient, so not written out by the serialisation
mechanism. There is good reason for this.

ArrayList (or AbstractList or something) provides a writeObject
implementation, that (after writing out the non-transient fields of the
class through defaultWriteObject) writes the data out in a way that is
independent of the way it is represented in the real object.

As well as giving a fractional speed and space improvement, this allows
for the implementation to be changed between versions. Using a similar
technique HashMap moved from always trying to have a prime size for its
array, to always having a power of two (and it can also cope with
deserialising keys which do not persist hash code).

You can tell the data gets written somehow, because my example works. As
do lots of other pieces of code written over the last decade.

Tom Hawtin
scifluent@gmail.com - 24 Mar 2007 21:45 GMT
Thank you Tom and thank you Patricia!  The cleaner implementation
provided by Tom is resulting in my element data coming through!!

Thanks!!!
Patricia Shanahan - 24 Mar 2007 21:06 GMT
> I am serializing an arraylist using the following code:
...

> ... and when I read it back in using the code below...I get the
> correct number of elements in the ArrayList but the elements are all
> nulll values.  Any ideas???  (I have verified that the orginal list
> has non-null element values.)  Thanks!!!!

Perhaps an issue with the (de)serialization code for the content?

I tried the following, with a String and an Integer in my ArrayList, and
it works, with output:

java.lang.String xxx
java.lang.Integer 3

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerialTest {

  public static void main(String[] args) throws IOException,
ClassNotFoundException {
    // Create an ArrayList with some serializable content
    ArrayList l1 = new ArrayList();
    l1.add("xxx");
    l1.add(new Integer(3));

    // Serialize l1 into a byte[]
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(outBytes);
    out.writeObject(l1);
    out.close();
    byte[] data = outBytes.toByteArray();

    // Deserialize from byte[] into l2
    ByteArrayInputStream inBytes = new ByteArrayInputStream(data);
    ObjectInputStream in = new ObjectInputStream(inBytes);
    ArrayList l2 = (ArrayList)in.readObject();

    // Print the content of the deserialized list
    for(Object o: l2){
      if(o == null){
        System.out.println("null");
      }else{
        System.out.printf("%s %s%n",           
          o.getClass().getName(),o.toString());
      }
    }
  }
}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.