Solved

Reading and Writing to Vectors

Posted on 2004-08-24
13
323 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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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 if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

708 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

20 Experts available now in Live!

Get 1:1 Help Now