Solved

Reading and Writing to Vectors

Posted on 2004-08-24
13
324 Views
Last Modified: 2011-09-20
I'm having problems reading and writing Objects to a Vector. My goal is to write several objects to a vector (scriptAddItemButtonActionPerformed), read the vector objects and write them to a file ( public void save())  and then read the
objects from the file for display to a list box (private void open()). I did not include all the code to write the contents to a list box for clarity.

The results that I am getting is that only the last object in the Vector is being seen. It acts like only one memory allocation is done and their is a place holder for only one object. It appears when the vector is created, one memory address is allocated, whenever I read or write to the vector the vector address points to one location in memory.

Can anyone help me to understand how vectors are supposed to work.

Here is my code:

  scriptVector = new Vector(10,5);
  OutElement = new ScriptElement();
  InElement = new ScriptElement();
  listElementIndex = 0;

// Adds objects to a Vector - this action can be performed many times by an operator
    private void scriptAddItemButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        OutElement.setCameraID(CameraCommand.DVO_CAMERA_ID);
        OutElement.setParamID(CameraCommand.FR_PARAMID);
        OutElement.setParamValue(CameraCommand.FPS_1000);
       
        scriptVector.addElement(OutElement);
        listElementIndex++;
     }

   // Open File
    public void save()
    {
        jFileChooser1.setVisible(true);
        if (jFileChooser1.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        {
            save (jFileChooser1.getSelectedFile());
        }
    }
   
    private void save (File file)
    {
      try
      {
         // Write the objects stored in script vector to the specified file
         ObjectOutputStream Script = new ObjectOutputStream(new FileOutputStream(file));
         for (int i=0; i < listElementIndex ; i++)
         {
            Script.writeObject(scriptVector.get(i));
         }
         Script.flush();
         Script.close();
      }
      catch (IOException ex)
      {
        jlblStatus.setText("Error saving " + file.getName());
      }
   }
       
   /** Open file */
  private void open()
  {
     Object newItem = scriptSelectComboBox.getSelectedItem();
     int scriptCount = 0;
     boolean eof = false;
     try
     {
        // Read from the specified file and store it in a vector
        ObjectInputStream InStream = new ObjectInputStream(new FileInputStream(myFileRef.getPath() + "//scripts//" + newItem.toString()));
        scriptVector.clear();
        scriptVector.trimToSize();
        // Read script elements into a vector
        while (!eof)
        {
            scriptVector.addElement(InStream.readObject());
            scriptCount++;
        }
     }
     catch (IOException e)
     {
         for(int i = 0; i < scriptCount ; i++)
         {
            InElement = (ScriptElement)scriptVector.get(i);
            int camID = InElement.getCameraID();
            int iParamID = InElement.getParamID();
            int iParamValue = InElement.getParamValue();
            int plusTime = InElement.getPlusTime();
         }
     }
   }  



0
Comment
Question by:GoldStrike
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11882500
Just add the elements to the Vecctor then serialize the Vector
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11882509
why not just write the whole vector?

instead of writing all elements in turn and reading all elements in turn?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11882515
hah!  too slow :-(
0
 
LVL 1

Assisted Solution

by:SlimHealer
SlimHealer earned 75 total points
ID: 11883709
It looks to me like you are quite used to using arrays, and are treating vectors basically the same as arrays.  You can get quite a ways doing this, but in the long run they work better if you treat them as something simpler -- a collection of objects that one can iterate through.

You go to some effort to keep listElementIndex "up to date", then use it to access your vector.

Try instead to just use the Iterator that a vector returns to access your Vector.  Here's a bit of your code, rewritten to use Vectors more naturally:

 private void save (File file)
 {
   try
   {
    // Write the objects stored in script vector to the specified file
      ObjectOutputStream Script = new ObjectOutputStream(new FileOutputStream(file));
      for (Iterator i = scriptVector.iterator(); i.hasNext();) {
      ScriptElement elem = (ScriptElement) i.next();
         // System.err.println( elem ); // << -- for debugging to see what's going on
         Script.writeObject( elem);
      }
   }
   catch (IOException ex) {
     jlblStatus.setText("Error saving " + file.getName());
   }
  }

0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 125 total points
ID: 11883787
>>Try instead to just use the Iterator that a vector returns to access your Vector ...

Err.. except that does exactly what Tim and i have advised *not* to do ;-) i.e. makes several writeObject calls when only one is necessary.

You only need *one* writeObject call, the parameter being the Vector reference
0
 
LVL 1

Expert Comment

by:SlimHealer
ID: 11884865
I'm working more on the final request here, to wit:

  "Can anyone help me to understand how vectors are supposed to work?"

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:GoldStrike
ID: 11899151
CEHJ
"Just add the elements to the Vecctor then serialize the Vector"
How do I do this?

So to follow your leads.. the code would look like...
Here is my code:

  scriptVector = new Vector(10,5);
  OutElement = new ScriptElement();
  InElement = new ScriptElement();
 
// Adds objects to a Vector - this action can be performed many times by an operator
    private void scriptAddItemButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        OutElement.setCameraID(CameraCommand.DVO_CAMERA_ID);
        OutElement.setParamID(CameraCommand.FR_PARAMID);
        OutElement.setParamValue(CameraCommand.FPS_1000);
       
        scriptVector.addElement(OutElement)
     }

   // Open File
    public void save()
    {
        jFileChooser1.setVisible(true);
        if (jFileChooser1.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        {
            save (jFileChooser1.getSelectedFile());
        }
    }
   
    private void save (File file)
    {
      try
      {
         // Write the objects stored in script vector to the specified file
         ObjectOutputStream Script = new ObjectOutputStream(new FileOutputStream(file));
         Script.writeObject(scriptVector);
         
         Script.flush();
         Script.close();
      }
      catch (IOException ex)
      {
        jlblStatus.setText("Error saving " + file.getName());
      }
   }
       
   /** Open file */
  private void open()
  {
     Object newItem = scriptSelectComboBox.getSelectedItem();
     int scriptCount = 0;
     boolean eof = false;
     try
     {
        // Read from the specified file and store it in a vector
        ObjectInputStream InStream = new ObjectInputStream(new FileInputStream(myFileRef.getPath() + "//scripts//" + newItem.toString()));
        scriptVector.clear();
        scriptVector.trimToSize();
        // Read script elements into a vector
        scriptVector = InStream.readObject();
                 
     }
     catch (IOException e)
     {
         for(int i = 0; i < scriptVector.size() ; i++)
         {
            InElement = (ScriptElement)scriptVector.get(i);
            int camID = InElement.getCameraID();
            int iParamID = InElement.getParamID();
            int iParamValue = InElement.getParamValue();
            int plusTime = InElement.getPlusTime();
         }
     }
   }  


0
 
LVL 35

Accepted Solution

by:
TimYates earned 50 total points
ID: 11900130
>         scriptVector = InStream.readObject();

should be

        scriptVector = (Vector)InStream.readObject();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11901606
>>So to follow your leads.. the code would look like...

Yes indeed - with the correction Tim mentioned. In Java, you variable names should begin with a lower case letter or the code becomes confusing
0
 

Author Comment

by:GoldStrike
ID: 11915875
Ok, thanks, that appears to work.
Now keeping the same theme (Vectors), how do I keep from adding duplicate objects to the vector?
Do I need to iterate through the vector?

           
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11916078
No you needn't do that. If you need to keep it as a Vector, then you can do:

if (v.contains(candidateObject) == false) {
    // add it
}

If you used a Set, this would happen automatically. The objects in the Vector should implement equals(Object other) properly
0
 

Author Comment

by:GoldStrike
ID: 11933077
CEHJ
Ok, I'll give it a try
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11968960
;-)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mapAB Challlenge 35 123
Java Message handling in Service Layer 3 55
VB Script to add site to Java Exception List 4 48
print map entry 34 53
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now