?
Solved

Reading and Writing to Vectors

Posted on 2004-08-24
13
Medium Priority
?
330 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 1

Assisted Solution

by:SlimHealer
SlimHealer earned 300 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 500 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 200 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
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 about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month14 days, 6 hours left to enroll

801 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