[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 334
  • Last Modified:

Reading and Writing to Vectors

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
GoldStrike
Asked:
GoldStrike
  • 5
  • 3
  • 3
  • +1
3 Solutions
 
CEHJCommented:
Just add the elements to the Vecctor then serialize the Vector
0
 
TimYatesCommented:
why not just write the whole vector?

instead of writing all elements in turn and reading all elements in turn?
0
 
TimYatesCommented:
hah!  too slow :-(
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
SlimHealerCommented:
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
 
CEHJCommented:
>>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
 
SlimHealerCommented:
I'm working more on the final request here, to wit:

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

0
 
GoldStrikeAuthor Commented:
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
 
TimYatesCommented:
>         scriptVector = InStream.readObject();

should be

        scriptVector = (Vector)InStream.readObject();
0
 
CEHJCommented:
>>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
 
GoldStrikeAuthor Commented:
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
 
CEHJCommented:
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
 
GoldStrikeAuthor Commented:
CEHJ
Ok, I'll give it a try
0
 
CEHJCommented:
;-)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 5
  • 3
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now