Solved

Reading and Writing to Vectors

Posted on 2004-08-24
13
325 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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
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
 

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

ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
maven project error 5 56
How to monitor the number of connections/threads being utilized on Tomcat 6.0 8 71
diffSum example 4 37
arguments to jar 5 26
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

822 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