Q: readObject(), array?

class Eph2000F extends Frame implements ActionListener, WindowListener, Runnable
{ public void actionPerformed(ActionEvent AE) //===============================================
{ if(AE.getSource()==MI_Avaa) //open
{ FileDialog f=new FileDialog(this,"Avaa Examiphobia-tiedosto (*.eph)",FileDialog.LOAD);
f.show();
tiedosto=f.getFile(); //file
polku=f.getDirectory(); //path
lueTiedot();
KysymysLuokka Kysymykset[]; //questionclass questions[]
static class KysymysLuokka implements Serializable { ... }
public void lueTiedot() //readData()
{ if(tiedosto!=""&&tiedosto!=null&&polku!=""&&polku!=null)
{ f=new File(polku+tiedosto);
if(!f.exists()) { ilmoita("Tiedosto ei ole olemassa!"); return; } //tell to user...
else if(f.isDirectory()) { ilmoita("Tiedosto on hakemisto!"); return; }
else if(!f.canWrite()) { ilmoita("Tiedosto on kirjoitus-suojattu!"); return; }
try
{ FileInputStream FIS=new FileInputStream(f);
ObjectInputStream OIS=new ObjectInputStream(FIS);
Kysymykset=new KysymysLuokka[1];
Kysymykset[0]=new KysymysLuokka();
kysymysNyt=0; //question now
Kysymykset=(KysymysLuokka[])OIS.readObject(); //-> to catch, because Kysymykset=null!!!
OIS.close(); out("OIS.close() suoritettu");
kysymysNyt=0; out("kysymysNyt=0; suoritettu");
catch(Exception E) { ilmoita("Deserialisointi ei onnistunut..."); } //it comes here.
Hi! where's the problem. this is ver 2.00 of eph; and ver 1.00 worked correctly.
I just can't find the problem. kysymykset = null, why

Have you checked so that you havent serialized it as
null?Thanks, I think you are right, that I should check null-selialization. I must have algoritm-problem with save-method(), it propably saves object as null and there's nothing...
Otherwise I would recomend to put in traces and see
were you get it set to null.
By the way, do you get exceptions on this one? yes; lueTiedot()-> nullPointerException

Similar Messages

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

  • Strange issue with POF: byte array with the value 94

    This is a somewhat strange issue we’ve managed to reduce to this test case. We’ve also seen similar issues with chars and shorts as well. It’s only a problem if the byte value inside the byte array is equal to 94! A value of 93, 95, etc, seems to be ok.
    Given the below class, the byte values both in the array and the single byte value are wrong when deserializing. The value inside the byte array isn’t what we put in (get [75] instead of [94]) and the single byte value is null (not 114).
    Pof object code:
    package com.test;
    import java.io.IOException;
    import java.util.Arrays;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    public class PofObject1 implements PortableObject {
         private byte[] byteArray;
         private byte byteValue;
         public void setValues() {
              byteArray = new byte[] {94};
              byteValue = 114;
         @Override
         public void readExternal(PofReader reader) throws IOException {
              Object byteArray = reader.readObjectArray(0, null);
              Object byteValue = reader.readObject(1);
              System.out.println(Arrays.toString((Object[])byteArray));
              System.out.println(byteValue);
              if (byteValue == null) throw new IOException("byteValue is null!");
         @Override
         public void writeExternal(PofWriter writer) throws IOException {
              writer.writeObject(0, byteArray);
              writer.writeObject(1, byteValue);
    Using writer.writeObjectArray(0, byteArray); instead of writer.writeObject(0, byteArray); doesn't help. In this case byteArray would be of type Object[] (as accessed through reflection).
    This is simply put in to a distributed cache and then fetched back. No EPs, listeners or stuff like that involved:
         public static void main(String... args) throws Exception {
              NamedCache cache = CacheFactory.getCache("my-cache");
              PofObject1 o = new PofObject1();
              o.setValues();
              cache.put("key1", o);
              cache.get("key1");
    Only tried it with Coherecne 3.7.1.3.
    Cache config file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE cache-config SYSTEM "cache-config.dtd">
    <cache-config>
         <caching-scheme-mapping>
              <cache-mapping>
                   <cache-name>my-cache</cache-name>
                   <scheme-name>my-cache</scheme-name>
              </cache-mapping>
         </caching-scheme-mapping>
         <caching-schemes>
              <distributed-scheme>
                   <scheme-name>my-cache</scheme-name>
                   <service-name>my-cache</service-name>
                   <serializer>
                        <class-name>
                             com.tangosol.io.pof.ConfigurablePofContext
                        </class-name>
                        <init-params>
                             <init-param>
                                  <param-type>string</param-type>
                                  <param-value>pof-config.xml</param-value>
                             </init-param>
                        </init-params>
                   </serializer>
                   <lease-granularity>thread</lease-granularity>
                   <thread-count>10</thread-count>
                   <backing-map-scheme>
                        <local-scheme>
                        </local-scheme>
                   </backing-map-scheme>
                   <autostart>true</autostart>
              </distributed-scheme>
         </caching-schemes>
    </cache-config>
    POF config file:
    <?xml version="1.0"?>
    <pof-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.oracle.com/coherence/coherence-pof-config"
         xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-pof-config coherence-pof-config.xsd">
         <user-type-list>
              <!-- coherence POF user types -->
              <include>coherence-pof-config.xml</include>
              <user-type>
                   <type-id>1460</type-id>
                   <class-name>com.test.PofObject1</class-name>
              </user-type>
         </user-type-list>
    </pof-config>

    Hi,
    POF uses certain byte values as an optimization to represent well known values of certain Object types - e.g. boolean True and False, some very small numbers, null etc... When you do read/write Object instead of using the correct method I suspect POF gets confused over the type and value that the field should be.
    There are a number of cases where POF does not know what the type is - Numbers would be one of these, for example if I stored a long of value 10 on deserialization POF would not know if that was an int, long double etc... so you have to use the correct method to get it back. Collections are another - If you serialize a Set all POF knows is that you have serialized some sort of Collection so unless you are specific when deserializing you will get back a List.
    JK

  • Cannot deserialize array in Netscape 4.7

    Im trying to deserialize an object that has been assed from servlet to applet with an int[]. When i execute (int[])is.readObject in Netscape (in MSExplorer works fine) the error in java console is:
    java.lang.NullPointerException
    at java.io.ObjectInputStream.inputArray(Compiled Code)
    at java.io.ObjectInputStream.readObject(Compiled Code)
    at IICR.web.util.IICRSerializableImage.readObject(Compiled Code)
    at java.io.ObjectInputStream.inputObject(Compiled Code)
    * at java.io.ObjectInputStream.readObject(Compiled Code)
    at IICR.web.util.IICRRotacionImageApplet.obtenerImagen(Compiled Code)
    at IICR.web.util.IICRRotacionImageApplet.init(Compiled Code)
    at netscape.applet.DerivedAppletFrame$InitAppletEvent.dispatch(Compiled Code)
    at java.awt.EventDispatchThread$EventPump.dispatchEvents(Compiled Code)
    at java.awt.EventDispatchThread.run(Compiled Code)
    at netscape.applet.DerivedAppletFrame$AppletEventDispatchThread.run(Compiled Code)

    Hi,
    i never did int[].readObject(), so I'm not sure if it works.
    what I do normally is the following:
    o.writeObject(array.length);
    for(int i=0; i<array.length; i++) {
      o.writeObject(array;
    int size = o.readObject();
    String[] array = new String[size];
    for(int i=0; i<= size; i++) {
      array[i] = (String)o.readObject();
    }attention: This code does not care of null arrays

  • Exception during receive an array bytes from servlet

    Hi! I have some problem with receive my array bytes. When I want to recive my array bytes at application site from servlet, I have an exception java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) near ObjectInputStream. I don't know what it's make. All looks good. Strings send I recive without any problems. Problem is with array bytes.
    URL url = new URL("http://127.0.0.1/App/servlet/Serwlet");
             URLConnection connect = url.openConnection();
            connect.setUseCaches(false);
             connect.setDefaultUseCaches(false);
             connect.setDoOutput(true);
         connect.setDoInput(true);    
    connect.setRequestProperty("Content-Type","application/x-java-serialized-object");
    ObjectOutputStream out = new sdfgObjectOutputStream(connect.getOutputStream());
              out.writeObject(arrayBytes);
              out.flush();
              out.close();
    //Here during debug is an exception
    ObjectInputStream in = new ObjectInputStream(connect.getInputStream());
              byte[] tmp = (byte[])in.readObject();
              in.close();
    System.out.println("Send array: "+arrayBytes);    
    System.out.println("Receive array: "+tmp);
    Servlet site :
    ObjectInputStream in = new ObjectInputStream(request.getInputStream());
                   byte[] tmp = (byte[])in.readObject();
                   in.close();
    response.setContentType("application/octet-stream");
                   ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
                   out.writeObject(tmp);
                   out.flush();
                   out.close();Any ideas? :]

    All this exception looks that :
    java.io.EOFException
         at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
         at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
         at java.io.ObjectInputStream.<init>(Unknown Source)
         at Klient.OdbiorcaButton.polaczenie(OdbiorcaButton.java:151)
         at Klient.OdbiorcaButton.actionPerformed(OdbiorcaButton.java:124)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • Reading an Array of Objects from a .bin file!

    Hey, at the moment I'm creating a program whereby I write a set of objects onto a bin file, in this case an array of objects with a String name/county, and int population/area.... I'm not trying to read it back from the bin file and encountering trouble! I've managed to get it working using plain objects, however I want to be able to read in arrays of objects. The file itself compiles, however during running I get this error
    java.lang.NullPointerException
    at RecordFiles.CoastalRead.main(CoastalRead.java:33)
    at RecordFiles.__SHELL16.run(__SHELL16.java:6)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
    Here is the program itself,
    import java.io.*;
    public class CoastalRead {
        public static void main(String[] args) {
            CoastalTowns towns[] = new CoastalTowns[50];
              towns[0] = new CoastalTowns();
              towns[1] = new CoastalTowns();
              towns[2] = new CoastalTowns();
              towns[3] = new CoastalTowns();
              towns[4] = new CoastalTowns();
              String name, county;
              int population, area;
            try {
                FileInputStream fileIn =
                        new FileInputStream("CoastalTownsBin.bin");
                ObjectInputStream in = new ObjectInputStream(fileIn);
                for (int i = 0; i < towns.length; i++){
                 towns[i] =(CoastalTowns) in.readObject();
                   System.out.println("Deserialized File...");
                       System.out.println("Name: " + towns.name);
              System.out.println("County: " + towns[i].county);
         System.out.println("Population: " + towns[i].population);
              System.out.println("Area: " + towns[i].area);
    in.close();
    fileIn.close();
    } catch (IOException i) {}
    catch (ClassNotFoundException c) {}
    +I'd appreciate a fast reply!+ And if someone needs the writing class I've used, I can post it asap.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    CoastalTowns towns[] = new CoastalTowns[50];
    towns[0] = new CoastalTowns();
    towns[1] = new CoastalTowns();
    towns[2] = new CoastalTowns();
    towns[3] = new CoastalTowns();
    towns[4] = new CoastalTowns();Why create an array with a size of 50 and then only fill 5 elements?
    Why bother filling any elements at all when you are reading the objects from a file?
    What happens if there are less than 50 objects in your file?
    I will assume CoastalTowns holds info about a single town, so why is it pluralised? Do you have a class called Dog or Dogs, Chair or Chairs, Person or People?
    } catch (IOException i) {}
    catch (ClassNotFoundException c) {}DO NOT swallow exceptions. At the very least put in a call to printStackTrace so you know if/when an exception occurs.
    I'd appreciate a fast reply!I typed as fast as I could but unfortunately I'm still and hunt and peck guy.

  • Storing an Array in the EncryptedLocalStore

    <!-- Fist of all, excuse my poor English, I'm doing my best. -->
    Hi ppl!
    I'm trying to store an array plenty of strings in the EncryptedLocalStore but it doesn't work. I think there is some kind of problem when retrieving data from the store and casting it into an array.
    There are no runtime/compilation errors but I can't read the strings I used to store.
    Here is the code I'm using to store the array:
    bytes = new ByteArray();
    bytes.writeObject(myArray) as Array;
    EncryptedLocalStore.setItem("arrayStored", bytes);
    And here, the code to read it:
    readArray = EncryptedLocalStore.getItem("arrayStored").readObject() as Array;
    Can someone help me? Thanks!

    Please, any trails or ideas?

  • Writing int [ ] Array in a file

    Hye
    Can you tell me which Stream I can use to write an Integer Array (defined as int [ 7000]) in a file .txt
    I want to write as a whole not one by one.
    Thanks

    import java.util.Vector;
    import java.io.*;
    public class Queue extends Vector {
      ** FIFO, first in first out
      Queue() {
      super();
    void put(Object o) {
      addElement(o);
    Object get() {
      if (isEmpty()) return null;
        Object o = firstElement();
        removeElement(o);
        return o;
    Object peek() {
      if (isEmpty()) return null;
        return firstElement();
    To serialize (save the Queue state to a file) :
    public static void main(String args[]) {
      Queue theQueue;
      theQueue = new Queue();
      theQueue.put(new int[]{1, 2, 3, 4});
      theQueue.put("ABCDE");
      theQueue.put(new Integer(3));
      System.out.println(theQueue.toString());
      // serialize the Queue
      System.out.println("serializing theQueue");
      try {
          FileOutputStream fout = new FileOutputStream("thequeue.dat");
          ObjectOutputStream oos = new ObjectOutputStream(fout);
          oos.writeObject(theQueue);
          oos.close();
       catch (Exception e) { e.printStackTrace(); }
    To unserialize (to load a previously saved Queue) :
    public static void main(String args[]) {
       Queue theQueue;
       theQueue = new Queue();
       // unserialize the Queue
       System.out.println("unserializing theQueue");
       try {
        FileInputStream fin = new FileInputStream("thequeue.dat");
        ObjectInputStream ois = new ObjectInputStream(fin);
        theQueue = (Queue) ois.readObject();
        ois.close();
       catch (Exception e) { e.printStackTrace(); }
       System.out.println(theQueue.toString());    
    }hope that helps

  • Object array input

    Hello, I am trying to input a file that contains an array of object refrences. When doing so I set the array to receive the input array to a larger size than the array being input. Once the array is input however, it resizes the created array to the size of the input array. For instance, I create an array size 10. Input and array size 5. The length of the created array will now be 5. I caught it by using this check:
    System.out.println(shapes.length);
    shapes = (MyShape[]) objectIn.readObject();
    System.out.println(shapes.length);
    Any help would be appreciated.
    Thanks,
    Matt

    Hello, I am trying to input a file that contains an
    array of object refrences. When doing so I set the
    array to receive the input array to a larger size
    than the array being input.How do you know it's larger than what's being input? It might be better to use (for example) a Vector so that the array grows automatically as you add items.
    Once the array is input
    however, it resizes the created array to the size of
    the input array. For instance, I create an array
    size 10. Input and array size 5. The length of the
    created array will now be 5. I caught it by using
    this check:
    System.out.println(shapes.length);
    shapes = (MyShape[]) objectIn.readObject();
    System.out.println(shapes.length);It's a bit unclear what your problem is... can you post more code and/or errors?

  • This byte array is not garbage collected?

    imageBytes[] does not seem to ever be garbage collected. I've pinpointed a SINGLE LINE that, when commented out, will prevent the memory leak. What could possibly be wrong with this line?
    Running this code results in a "OutOfMemoryError: Java heap space" after roughly a minute on my machine. I'm using JRE version 1.5.0_08.
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    // creates images to send to ImageConsumer
    public class ImageProducer {
         static BufferedImage bufferedImage;
         static Robot robo;
         static byte[] imageBytes;
         public static void main(String args[]) {
              try {
                   robo = new Robot();
              } catch(Exception e) {
                   e.printStackTrace();
              PipedOutputStream pos = new PipedOutputStream();
              new ImageConsumer(pos).start();
              bufferedImage = robo.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
              try {
                   ObjectOutputStream oostream = new ObjectOutputStream(pos);
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   ImageIO.write(bufferedImage, "JPG", baos);
                   baos.flush();
                   imageBytes = baos.toByteArray();
                   while (true) {
                        ImageIO.write(bufferedImage, "JPG", baos);
                        baos.flush();
                        // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
                        // If you comment the following line out, there will be no
                        // memory leak. Why?  I ask that you help me solve this.
                        imageBytes = baos.toByteArray();
                        baos.reset();
                        oostream.writeObject(imageBytes);
                        pos.flush();
              } catch (Exception e) {
                   e.printStackTrace();
    // This thread reads the image data into bImg
    class ImageConsumer extends Thread {
         BufferedImage bImg;
         PipedInputStream pis;
         ImageConsumer(PipedOutputStream pos) {
              try {
                   pis = new PipedInputStream(pos);
              } catch (IOException e) { e.printStackTrace();}
         public void run() {
              try {
                   ObjectInputStream oinstream = new ObjectInputStream(pis);
                   while (true) {
                        byte[] imageBytes = (byte[])oinstream.readObject();
                        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
                        bImg = ImageIO.read(bais);
              } catch (Exception e) {e.printStackTrace();}
    }

    while (true) {
         ImageIO.write(bufferedImage, "JPG", baos);
         baos.flush();
         // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
         // If you comment the following line out, there will be no
         // memory leak. Why? I ask that you help me solve this.
         imageBytes = baos.toByteArray();
         baos.reset();
         oostream.writeObject(imageBytes);
         pos.flush();
    }I have only briefly gone through the code, but why are you flushing it right before calling that line. Won't the byte array returned always be empty right after flushing the stream?

  • Outputting an Array

    Ive created an array in my program with 3 values. Im stuck as i have to output a specific value from the array, say value 2 to a text display on my GUI.
    Ive tried but i cant figure it out. Can anyone help me?
    Cheers

    Thanks, getting there.
    I just get an error now :(
    ---------- javac ----------
    IVA3ArraysVersion.java:509: cannot find symbol
    symbol  : variable temps
    location: class IVA3ArraysVersion
              display.setText(String.valueOf(temps[1]));     
                                                   ^
    1 error
    Output completed (1 sec consumed) - Normal TerminationMaybe im setting up the array wrong.
    This is all the code that i have done for the array.
         //Data
         int [] temps= new int [3];     
         temps[0] = 2;
         temps[1] = 4;       
         temps[2] = 2;
         // save array
         try
              fos = new FileOutputStream("temps.dat");
              oos = new ObjectOutputStream(fos);
              oos.writeObject(temps); 
              oos.flush();
              oos.close();
              catch(IOException ex)
              System.out.println("error writing: " + ex.getMessage());
         // load and print array
         try
              fis = new FileInputStream("temps.dat");
              ois = new ObjectInputStream(fis);
              int[] temps2 = (int [])ois.readObject();               
              ois.close();                    
              catch(IOException ex) // required
                   System.out.println("error reading: " + ex.getMessage()); // for debugging
              catch(ClassNotFoundException ex) // required
                   System.out.println("error reading: " + ex.getMessage()); // for debugging
              }My first proper attempt at using arrays.
    Thanks

  • Dynamic Array resizing

    I have a class with some data members in it. Data for the objects comes frm a XML file. I have to parse out the xml file and create objects. Before reading the XML file i dunno as to how many objects i need to create. I wud like to know a way where I can dynamically increase the size of the object array as I read through the XMl file.
    Thanks in advance,
    Kris.

    This is the source:
    * @(#)ArrayList.java     1.36 01/12/03
    * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    package java.util;
    * Resizable-array implementation of the <tt>List</tt> interface.  Implements
    * all optional list operations, and permits all elements, including
    * <tt>null</tt>.  In addition to implementing the <tt>List</tt> interface,
    * this class provides methods to manipulate the size of the array that is
    * used internally to store the list.  (This class is roughly equivalent to
    * <tt>Vector</tt>, except that it is unsynchronized.)<p>
    * The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
    * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
    * time.  The <tt>add</tt> operation runs in <i>amortized constant time</i>,
    * that is, adding n elements requires O(n) time.  All of the other operations
    * run in linear time (roughly speaking).  The constant factor is low compared
    * to that for the <tt>LinkedList</tt> implementation.<p>
    * Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
    * the size of the array used to store the elements in the list.  It is always
    * at least as large as the list size.  As elements are added an ArrayList,
    * its capacity grows automatically.  The details of the growth policy are not
    * specified beyond the fact that adding an element has constant amortized
    * time cost.<p>
    * An application can increase the capacity of an <tt>ArrayList</tt> instance
    * before adding a large number of elements using the <tt>ensureCapacity</tt>
    * operation.  This may reduce the amount of incremental reallocation.<p>
    * <strong>Note that this implementation is not synchronized.</strong> If
    * multiple threads access an <tt>ArrayList</tt> instance concurrently, and at
    * least one of the threads modifies the list structurally, it <i>must</i> be
    * synchronized externally.  (A structural modification is any operation that
    * adds or deletes one or more elements, or explicitly resizes the backing
    * array; merely setting the value of an element is not a structural
    * modification.)  This is typically accomplished by synchronizing on some
    * object that naturally encapsulates the list.  If no such object exists, the
    * list should be "wrapped" using the <tt>Collections.synchronizedList</tt>
    * method.  This is best done at creation time, to prevent accidental
    * unsynchronized access to the list:
    * <pre>
    *     List list = Collections.synchronizedList(new ArrayList(...));
    * </pre><p>
    * The iterators returned by this class's <tt>iterator</tt> and
    * <tt>listIterator</tt> methods are <i>fail-fast</i>: if list is structurally
    * modified at any time after the iterator is created, in any way except
    * through the iterator's own remove or add methods, the iterator will throw a
    * ConcurrentModificationException.  Thus, in the face of concurrent
    * modification, the iterator fails quickly and cleanly, rather than risking
    * arbitrary, non-deterministic behavior at an undetermined time in the
    * future.
    * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
    * as it is, generally speaking, impossible to make any hard guarantees in the
    * presence of unsynchronized concurrent modification.  Fail-fast iterators
    * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
    * Therefore, it would be wrong to write a program that depended on this
    * exception for its correctness: <i>the fail-fast behavior of iterators
    * should be used only to detect bugs.</i>
    * @author  Josh Bloch
    * @version 1.36, 12/03/01
    * @see         Collection
    * @see         List
    * @see         LinkedList
    * @see         Vector
    * @see         Collections#synchronizedList(List)
    * @since   1.2
    public class ArrayList extends AbstractList
            implements List, RandomAccess, Cloneable, java.io.Serializable
        private static final long serialVersionUID = 8683452581122892189L;
         * The array buffer into which the elements of the ArrayList are stored.
         * The capacity of the ArrayList is the length of this array buffer.
        private transient Object elementData[];
         * The size of the ArrayList (the number of elements it contains).
         * @serial
        private int size;
         * Constructs an empty list with the specified initial capacity.
         * @param   initialCapacity   the initial capacity of the list.
         * @exception IllegalArgumentException if the specified initial capacity
         *            is negative
        public ArrayList(int initialCapacity) {
         super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
         this.elementData = new Object[initialCapacity];
         * Constructs an empty list with an initial capacity of ten.
        public ArrayList() {
         this(10);
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.  The <tt>ArrayList</tt> instance has an initial capacity of
         * 110% the size of the specified collection.
         * @param c the collection whose elements are to be placed into this list.
         * @throws NullPointerException if the specified collection is null.
        public ArrayList(Collection c) {
            size = c.size();
            // Allow 10% room for growth
            elementData = new Object[
                          (int)Math.min((size*110L)/100,Integer.MAX_VALUE)];
            c.toArray(elementData);
         * Trims the capacity of this <tt>ArrayList</tt> instance to be the
         * list's current size.  An application can use this operation to minimize
         * the storage of an <tt>ArrayList</tt> instance.
        public void trimToSize() {
         modCount++;
         int oldCapacity = elementData.length;
         if (size < oldCapacity) {
             Object oldData[] = elementData;
             elementData = new Object[size];
             System.arraycopy(oldData, 0, elementData, 0, size);
         * Increases the capacity of this <tt>ArrayList</tt> instance, if
         * necessary, to ensure  that it can hold at least the number of elements
         * specified by the minimum capacity argument.
         * @param   minCapacity   the desired minimum capacity.
        public void ensureCapacity(int minCapacity) {
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
             Object oldData[] = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
                 if (newCapacity < minCapacity)
              newCapacity = minCapacity;
             elementData = new Object[newCapacity];
             System.arraycopy(oldData, 0, elementData, 0, size);
         * Returns the number of elements in this list.
         * @return  the number of elements in this list.
        public int size() {
         return size;
         * Tests if this list has no elements.
         * @return  <tt>true</tt> if this list has no elements;
         *          <tt>false</tt> otherwise.
        public boolean isEmpty() {
         return size == 0;
         * Returns <tt>true</tt> if this list contains the specified element.
         * @param elem element whose presence in this List is to be tested.
         * @return  <code>true</code> if the specified element is present;
         *          <code>false</code> otherwise.
        public boolean contains(Object elem) {
         return indexOf(elem) >= 0;
         * Searches for the first occurence of the given argument, testing
         * for equality using the <tt>equals</tt> method.
         * @param   elem   an object.
         * @return  the index of the first occurrence of the argument in this
         *          list; returns <tt>-1</tt> if the object is not found.
         * @see     Object#equals(Object)
        public int indexOf(Object elem) {
         if (elem == null) {
             for (int i = 0; i < size; i++)
              if (elementData==null)
              return i;
         } else {
         for (int i = 0; i < size; i++)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the index of the last occurrence of the specified object in
    * this list.
    * @param elem the desired element.
    * @return the index of the last occurrence of the specified object in
    * this list; returns -1 if the object is not found.
    public int lastIndexOf(Object elem) {
         if (elem == null) {
         for (int i = size-1; i >= 0; i--)
              if (elementData[i]==null)
              return i;
         } else {
         for (int i = size-1; i >= 0; i--)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
    * elements themselves are not copied.)
    * @return a clone of this <tt>ArrayList</tt> instance.
    public Object clone() {
         try {
         ArrayList v = (ArrayList)super.clone();
         v.elementData = new Object[size];
         System.arraycopy(elementData, 0, v.elementData, 0, size);
         v.modCount = 0;
         return v;
         } catch (CloneNotSupportedException e) {
         // this shouldn't happen, since we are Cloneable
         throw new InternalError();
    * Returns an array containing all of the elements in this list
    * in the correct order.
    * @return an array containing all of the elements in this list
    *      in the correct order.
    public Object[] toArray() {
         Object[] result = new Object[size];
         System.arraycopy(elementData, 0, result, 0, size);
         return result;
    * Returns an array containing all of the elements in this list in the
    * correct order; the runtime type of the returned array is that of the
    * specified array. If the list fits in the specified array, it is
    * returned therein. Otherwise, a new array is allocated with the runtime
    * type of the specified array and the size of this list.<p>
    * If the list fits in the specified array with room to spare (i.e., the
    * array has more elements than the list), the element in the array
    * immediately following the end of the collection is set to
    * <tt>null</tt>. This is useful in determining the length of the list
    * <i>only</i> if the caller knows that the list does not contain any
    * <tt>null</tt> elements.
    * @param a the array into which the elements of the list are to
    *          be stored, if it is big enough; otherwise, a new array of the
    *           same runtime type is allocated for this purpose.
    * @return an array containing the elements of the list.
    * @throws ArrayStoreException if the runtime type of a is not a supertype
    * of the runtime type of every element in this list.
    public Object[] toArray(Object a[]) {
    if (a.length < size)
    a = (Object[])java.lang.reflect.Array.newInstance(
    a.getClass().getComponentType(), size);
         System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
    a[size] = null;
    return a;
    // Positional Access Operations
    * Returns the element at the specified position in this list.
    * @param index index of element to return.
    * @return the element at the specified position in this list.
    * @throws IndexOutOfBoundsException if index is out of range <tt>(index
    *           < 0 || index >= size())</tt>.
    public Object get(int index) {
         RangeCheck(index);
         return elementData[index];
    * Replaces the element at the specified position in this list with
    * the specified element.
    * @param index index of element to replace.
    * @param element element to be stored at the specified position.
    * @return the element previously at the specified position.
    * @throws IndexOutOfBoundsException if index out of range
    *          <tt>(index < 0 || index >= size())</tt>.
    public Object set(int index, Object element) {
         RangeCheck(index);
         Object oldValue = elementData[index];
         elementData[index] = element;
         return oldValue;
    * Appends the specified element to the end of this list.
    * @param o element to be appended to this list.
    * @return <tt>true</tt> (as per the general contract of Collection.add).
    public boolean add(Object o) {
         ensureCapacity(size + 1); // Increments modCount!!
         elementData[size++] = o;
         return true;
    * Inserts the specified element at the specified position in this
    * list. Shifts the element currently at that position (if any) and
    * any subsequent elements to the right (adds one to their indices).
    * @param index index at which the specified element is to be inserted.
    * @param element element to be inserted.
    * @throws IndexOutOfBoundsException if index is out of range
    *          <tt>(index < 0 || index > size())</tt>.
    public void add(int index, Object element) {
         if (index > size || index < 0)
         throw new IndexOutOfBoundsException(
              "Index: "+index+", Size: "+size);
         ensureCapacity(size+1); // Increments modCount!!
         System.arraycopy(elementData, index, elementData, index + 1,
                   size - index);
         elementData[index] = element;
         size++;
    * Removes the element at the specified position in this list.
    * Shifts any subsequent elements to the left (subtracts one from their
    * indices).
    * @param index the index of the element to removed.
    * @return the element that was removed from the list.
    * @throws IndexOutOfBoundsException if index out of range <tt>(index
    *           < 0 || index >= size())</tt>.
    public Object remove(int index) {
         RangeCheck(index);
         modCount++;
         Object oldValue = elementData[index];
         int numMoved = size - index - 1;
         if (numMoved > 0)
         System.arraycopy(elementData, index+1, elementData, index,
                   numMoved);
         elementData[--size] = null; // Let gc do its work
         return oldValue;
    * Removes all of the elements from this list. The list will
    * be empty after this call returns.
    public void clear() {
         modCount++;
         // Let gc do its work
         for (int i = 0; i < size; i++)
         elementData[i] = null;
         size = 0;
    * Appends all of the elements in the specified Collection to the end of
    * this list, in the order that they are returned by the
    * specified Collection's Iterator. The behavior of this operation is
    * undefined if the specified Collection is modified while the operation
    * is in progress. (This implies that the behavior of this call is
    * undefined if the specified Collection is this list, and this
    * list is nonempty.)
    * @param c the elements to be inserted into this list.
    * @return <tt>true</tt> if this list changed as a result of the call.
    * @throws IndexOutOfBoundsException if index out of range <tt>(index
    *          < 0 || index > size())</tt>.
    * @throws NullPointerException if the specified collection is null.
    public boolean addAll(Collection c) {
         modCount++;
         int numNew = c.size();
         ensureCapacity(size + numNew);
         Iterator e = c.iterator();
         for (int i=0; i<numNew; i++)
         elementData[size++] = e.next();
         return numNew != 0;
    * Inserts all of the elements in the specified Collection into this
    * list, starting at the specified position. Shifts the element
    * currently at that position (if any) and any subsequent elements to
    * the right (increases their indices). The new elements will appear
    * in the list in the order that they are returned by the
    * specified Collection's iterator.
    * @param index index at which to insert first element
    *          from the specified collection.
    * @param c elements to be inserted into this list.
    * @return <tt>true</tt> if this list changed as a result of the call.
    * @throws IndexOutOfBoundsException if index out of range <tt>(index
    *          < 0 || index > size())</tt>.
    * @throws NullPointerException if the specified Collection is null.
    public boolean addAll(int index, Collection c) {
         if (index > size || index < 0)
         throw new IndexOutOfBoundsException(
              "Index: "+index+", Size: "+size);
         int numNew = c.size();
         ensureCapacity(size + numNew); // Increments modCount!!
         int numMoved = size - index;
         if (numMoved > 0)
         System.arraycopy(elementData, index, elementData, index + numNew,
                   numMoved);
         Iterator e = c.iterator();
         for (int i=0; i<numNew; i++)
         elementData[index++] = e.next();
         size += numNew;
         return numNew != 0;
    * Removes from this List all of the elements whose index is between
    * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
    * elements to the left (reduces their index).
    * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
    * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
    * @param fromIndex index of first element to be removed.
    * @param toIndex index after last element to be removed.
    protected void removeRange(int fromIndex, int toIndex) {
         modCount++;
         int numMoved = size - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
    numMoved);
         // Let gc do its work
         int newSize = size - (toIndex-fromIndex);
         while (size != newSize)
         elementData[--size] = null;
    * Check if the given index is in range. If not, throw an appropriate
    * runtime exception.
    private void RangeCheck(int index) {
         if (index >= size || index < 0)
         throw new IndexOutOfBoundsException(
              "Index: "+index+", Size: "+size);
    * Save the state of the <tt>ArrayList</tt> instance to a stream (that
    * is, serialize it).
    * @serialData The length of the array backing the <tt>ArrayList</tt>
    * instance is emitted (int), followed by all of its elements
    * (each an <tt>Object</tt>) in the proper order.
    private synchronized void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
         // Write out element count, and any hidden stuff
         s.defaultWriteObject();
    // Write out array length
    s.writeInt(elementData.length);
         // Write out all elements in the proper order.
         for (int i=0; i<size; i++)
    s.writeObject(elementData[i]);
    * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
    * deserialize it).
    private synchronized void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
         // Read in size, and any hidden stuff
         s.defaultReadObject();
    // Read in array length and allocate array
    int arrayLength = s.readInt();
    elementData = new Object[arrayLength];
         // Read in all elements in the proper order.
         for (int i=0; i<size; i++)
    elementData[i] = s.readObject();

  • ContainsAllFilter on array property and GreaterFilter on DateTime property

    I am very new to Coherence, trying to learn... We're using Coherence 3.7, and trying to get ContainsAllFilter on string[] property and GreaterFilter on DateTime to work. Java side implements hashCode (using Arrays.equals and RawDateTime) and equals on my POF; dotnet side also implements GetHashCode and Equals; in both cases, filters return with 0 result collection. What am I doing wrong? Thank you very much!

    Thanks for the response. I have included my Java object below.....where in this would I convert to the SQL Timestamp? Do you mean, that I would be storing the SQLTimestamp rather than RawDateTime as part of this object?
    public class RflxJournalEntry implements PortableObject {
         public RflxJournalEntry(){}
         public enum JournalOperation
              INSERT,UPDATE,DELETE;
         private JournalOperation operationType;
        private RawDateTime operationTime;
         private String process;
         private String version;
         private String username;
         private String tradeId;
        private int sequenceId;
         private RflxJournaledTrade updateList;
        private RflxTrade trade;
         @SuppressWarnings("unchecked")
         @Override
         public void readExternal(PofReader reader) throws IOException {
              setOperationType(reader.readInt(0));
              setOperationTime(reader.readRawDateTime(1));
              setProcess(reader.readString(2));
              setUsername(reader.readString(3));
              setTradeId(reader.readString(4));
              setSequenceId(reader.readInt(5));
              setUpdateList((RflxJournaledTrade)reader.readObject(6));
              setTrade((RflxTrade)reader.readObject(7));
              setVersion(reader.readString(8));
         @Override
         public void writeExternal(PofWriter writer) throws IOException {
            writer.writeInt(0, getOperationType());
            writer.writeRawDateTime(1, getOperationTime());
            writer.writeString(2, getProcess());
            writer.writeString(3, getUsername());
            writer.writeString(4, getTradeId());
            writer.writeInt(5, getSequenceId());
            writer.writeObject(6, getUpdateList());
            writer.writeObject(7, getTrade());
            writer.writeString(8, getVersion());
         public void setOperationType(int operationType) {
              this.operationType = RflxJournalEntry.JournalOperation.values()[operationType];
         public int getOperationType() {
              return operationType.ordinal();
         public void setProcess(String process) {
              this.process = process;
         public String getProcess() {
              return process;
         public void setUsername(String username) {
              this.username = username;
         public String getUsername() {
              return username;
         public void setTradeId(String tradeId) {
              this.tradeId = tradeId;
         public String getTradeId() {
              return tradeId;
         public void setOperationTime(RawDateTime operationTime) {
              this.operationTime = operationTime;
         public RawDateTime getOperationTime() {
              return operationTime;
         public void setSequenceId(int sequenceId) {
              this.sequenceId = sequenceId;
         public int getSequenceId() {
              return sequenceId;
         public void setUpdateList(RflxJournaledTrade updateList) {
              this.updateList = updateList;
         public RflxJournaledTrade getUpdateList() {
              return updateList;
         public void setTrade(RflxTrade trade) {
              this.trade = trade;
         public RflxTrade getTrade() {
              return trade;
         public void setVersion(String version) {
              this.version = version;
         public String getVersion() {
              return version;
    }

  • Reading in a multi dimension binary array

    Greetings,
    I am attempting to read in a binary file which contains data in a 1440x320x7x2 array. The method I am currently attempting to use is DataInputStream. But, it seems this method can only return a single dimensional array. Any tips?
    TIA

    It depends how it was written. If it was written by calling writeObject() on the whole 4D array, then calling readObject() will give you that whole array back.
    If it was written by writing out individual elements with writeData, then you'll have to use readData and build up the array piecemeal.
    If it was something inbetween, like calling writObject 1440 times on the 3D arrays, then you'll have to do the inverse of that.
    See the pattern?

  • The file just won't load into array...Please Help!

    hi i need some help in loading a binary file into an array so that i can edit the data that was saved from previous run..
    i could save the file but after that when i try to load it back to memory...i can't...ie. all the information keyed in were lost...please help
    this is the Code for the loading process...
         public static void loadAircraft (ArrayList aircraft) {
              try {
                   FileInputStream filein = new FileInputStream(".\\Data\\Aircraft.bin");
                   ObjectInputStream objectin = new ObjectInputStream(filein);
                   Aircraft craft = (Aircraft) objectin.readObject();
                   aircraft.add(craft);
                   objectin.close();
                   filein.close();
              catch (Exception e) {}
         }the above code won't load anything into memory...is there a way for overcoming this?
    inside the Aircraft class there are four different data of which they contain two differen data types.
    one of which is String and the other three are in int.
    Awaiting for reply...thanks

    yes...its some objects of an array that i am trying to load back...
    erm...i'll show you the whole code maybe...
    //to reference the swing library
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    public class SetupAircraft {
         static ArrayList aircraft;
         public static void init () {
              aircraft = new ArrayList(5);
              loadAircraft(aircraft);
         //opens up another sub group while the user
         //entered 1 as his/her option in the SetupSystem
         //menu
         public static void Setup () {
              //this will create a string that is going to be displayed
              //in the input dialog box
              String menu = "  Please select an option:  \n"
                              +"----------------------------\n"
                              +"1) Add New Aircraft\n"
                              +"2) Edit Existing Aircraft\n"
                              +"3) List Aircraft\n"
                              +"4) Delete Existing Aircraft\n"
                              +"5) Save\n"
                              +"6) Return to Main Menu\n\n"
                              +"   Enter a number between 1-6\n";
              //declare a field named option for selection through menu
              int option = 0;
              //continue the loop until the user inputs the number 6
              do {
                   //error handling for the input from the menu
                   //if the input is not integer the error is caught and
                   //reassigning option to be 0
                   try {
                        option = Integer.parseInt(JOptionPane.showInputDialog(null, menu,
                                   "Setup Aircraft", JOptionPane.QUESTION_MESSAGE));
                   catch (NumberFormatException e) {
                        option = 0;
                   //determine which option the user has chosen
                   //and enters the respective section
                   switch (option) {
                        case 1: add(aircraft);
                                  break;
                        case 2: edit(aircraft);
                                  break;
                        case 3: list(aircraft);
                                  break;
                        case 4: //delete(aircraft);
                                  break;
                        case 5: save(aircraft);
                                  break;
                        case 6:     return;
                        default: JOptionPane.showMessageDialog(null, "Please enter a number between 1-6",
                                   "Alert", JOptionPane.ERROR_MESSAGE);
                                   option = 0;
              while (true);
         public static void add (ArrayList aircraft) {
              String type = "";
              int first = 0;
              int business = 0;
              int economy = 0;
              do {
                   try {
                        type = JOptionPane.showInputDialog(null,"Enter Aircraft Type", "Prompt for Type",
                        JOptionPane.QUESTION_MESSAGE);
                        try {
                             if(aircraft.contains(type)) {
                                  JOptionPane.showMessageDialog(null, type + " already exist!",
                                  "Error", JOptionPane.ERROR_MESSAGE);
                                  type = "-100";
                        catch (Exception e) {}
                        if (type=="-100");
                        else if (type.length()==0) {
                             JOptionPane.showMessageDialog(null, "Please enter an aircraft type",
                             "Error", JOptionPane.ERROR_MESSAGE);
                        else if (!(type.startsWith("-",3))) {
                             JOptionPane.showMessageDialog(null, "Please enter the aircraft type with XXX-XXX format where X is integer.",
                             "Error", JOptionPane.ERROR_MESSAGE);
                             type = "0";
                   //catch the input error that the user has produces.
                   catch (Exception e) {
                        return;
              while (!(type.startsWith("-",3)));
              //try to ask the user for the passenger's name and if the name field contains
              //no characters at all repeat the prompt for name field until the user presses
              //Cancel.
              try {
                   first = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter First Class Capacity",
                   "Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
              catch (Exception e) {
                   String error = "For input string:";
                   if (e.getMessage() == "null") {
                        return;
                   else if (e.getMessage().startsWith(error)) {
                        JOptionPane.showMessageDialog(null, "Please enter only numbers",
                        "Error", JOptionPane.ERROR_MESSAGE);
              try {
                   business = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Business Class Capacity",
                   "Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
              catch (Exception e) {
                   String error = "For input string:";
                   if (e.getMessage() == "null") {
                        return;
                   else if (e.getMessage().startsWith(error)) {
                        JOptionPane.showMessageDialog(null, "Please enter only numbers",
                        "Error", JOptionPane.ERROR_MESSAGE);
              try {
                   economy = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Economy Class Capacity",
                   "Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
              catch (Exception e) {
                   String error = "For input string:";
                   if (e.getMessage() == "null") {
                        return;
                   else if (e.getMessage().startsWith(error)) {
                        JOptionPane.showMessageDialog(null, "Please enter only numbers",
                        "Error", JOptionPane.ERROR_MESSAGE);
              Aircraft newAircraft = new Aircraft (type, first, business, economy);
              aircraft.add(newAircraft);
              JOptionPane.showMessageDialog(null, "Aircraft Sucessfully Added",
              "Successful", JOptionPane.INFORMATION_MESSAGE);
         public static void edit (ArrayList aircraft) {
              String type = "";
              int first = 0;
              int business = 0;
              int economy = 0;
              do {
                   try {
                        type = JOptionPane.showInputDialog(null, "Enter Aircraft Type to Edit",
                        "Prompt for Type", JOptionPane.QUESTION_MESSAGE);
                        if (type.length()==0) {
                             JOptionPane.showMessageDialog(null,"Please enter an aircraft type",
                             "Error",JOptionPane.ERROR_MESSAGE);
                        else if (!(type.startsWith("-",3))) {
                             JOptionPane.showMessageDialog(null, "Please enter the aircraft type with XXX-XXX format where X is integer.",
                             "Error", JOptionPane.ERROR_MESSAGE);
                             type = "0";
                   catch (Exception e) {
                        return;
              while (!(type.startsWith("-",3)));
              try {
                   int edited = aircraft.indexOf(new UniqueAircraft(type));
                   Aircraft craft = (Aircraft)aircraft.get(edited);
                   try {
                        first = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter First Class Capacity",
                        "Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
                   catch (Exception e) {
                        String error = "For input string:";
                        if (e.getMessage() == "null") {
                             return;
                        else if (e.getMessage().startsWith(error)) {
                             JOptionPane.showMessageDialog(null, "Please enter only numbers",
                             "Error", JOptionPane.ERROR_MESSAGE);
                   try {
                        business = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Business Class Capacity",
                        "Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
                   catch (Exception e) {
                        String error = "For input string:";
                        if (e.getMessage() == "null") {
                             return;
                        else if (e.getMessage().startsWith(error)) {
                             JOptionPane.showMessageDialog(null, "Please enter only numbers",
                             "Error", JOptionPane.ERROR_MESSAGE);
                   try {
                        economy = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Economy Class Capacity",
                        "Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
                   catch (Exception e) {
                        String error = "For input string:";
                        if (e.getMessage() == "null") {
                             return;
                        else if (e.getMessage().startsWith(error)) {
                             JOptionPane.showMessageDialog(null, "Please enter only numbers",
                             "Error", JOptionPane.ERROR_MESSAGE);
                   Aircraft newAircraft = new Aircraft (type, first, business, economy);
                   aircraft.add(newAircraft);
                   aircraft.add(newAircraft);
                   JOptionPane.showMessageDialog(null, "Successfully edited aircraft\n"+type+" to capacities\n"
                   +"First: "+first+"\n"+"Business: "+business+"\n"+"Economy: "+economy,
                   "Successful", JOptionPane.INFORMATION_MESSAGE);
              catch (Exception e) {
                   JOptionPane.showMessageDialog(null,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
         public static void list (ArrayList aircraft) {
              JOptionPane.showMessageDialog(null, aircraft.size()+" aircraft found", "Found",JOptionPane.INFORMATION_MESSAGE);
              Object[] aircrafts;
              aircrafts = aircraft.toArray();
              for (int i=0;i<aircraft.size();i++) {
                   Aircraft a = (Aircraft) aircrafts;
                   JOptionPane.showMessageDialog(null, a, "Aircrafts" + (i+1), JOptionPane.INFORMATION_MESSAGE);
         public static void save (ArrayList aircraft) {
              try {
                   FileOutputStream fileout = new FileOutputStream(".\\Data\\Aircraft.bin");
                   ObjectOutputStream objectout = new ObjectOutputStream(fileout);
                   Object[] aircrafts;
                   aircrafts = aircraft.toArray();
                   objectout.writeObject(aircrafts);
                   objectout.close();
                   fileout.close();
                   JOptionPane.showMessageDialog(null,aircraft.size()+" aircrafts saved", "Sucessful", JOptionPane.INFORMATION_MESSAGE);
              catch (IOException e) {
                   JOptionPane.showMessageDialog(null,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
         public static void loadAircraft (ArrayList aircraft) {
              try {
                   FileInputStream filein = new FileInputStream(".\\Data\\Aircraft.bin");
                   ObjectInputStream objectin = new ObjectInputStream(filein);
                   Aircraft craft = null;
                   while ((craft=(Aircraft)objectin.readObject())!=null) {
                        aircraft.add(craft);
                   objectin.close();
                   filein.close();
              catch (Exception e) {
                   JOptionPane.showMessageDialog(null,e.toString());
                   e.printStackTrace();
    i think thats a bit too long..but it would explain what i am trying to save...its linking to the class Aircraft tho...
    thanks...i appreciate your help...

Maybe you are looking for