I have written this bit of code is ArrayList better than Vector and if so how do i change it ????

i am thinking where ever vector is mentioned to change it to ArrayList

import java.util.Vector;
import java.io.*;


public class V_All_Std_Record 
{

  private Vector main_Vector = new Vector();

  public V_All_Std_Record()
 {
    try
{
      File std_File = new File("");
      String str = std_File.getAbsolutePath()+"\\Data Files\\Std_Rec.txt";
      ObjectInputStream obj_File = new ObjectInputStream(new
          FileInputStream(new File(str)));

      main_Vector = (Vector)obj_File.readObject();
      obj_File.close();
      System.out.println(main_Vector);

    }
catch(Exception ee)
{
      System.out.println("Student Data file not Found or there is no data in it");
    }



  }
  public static void main(String[] args) 
{
    V_All_Std_Record v_All_Std_Record1 = new V_All_Std_Record();
  }

  //returns all studentd records
  public Vector getAllRecords()
{
    return main_Vector;
  }

}

Code tags added. -Narue

Recommended Answers

All 3 Replies

>is ArrayList better than Vec
It depends on your needs. If you need a synchronized list and it has to be compatible with Java 1.1 then Vector is an option. Otherwise, ArrayList should be preferred, and Collections.synchronizedList will give you synchronization (which ArrayList does not have by default).

>how do i change it ????
Compare the API documentation on Vector and ArrayList. That will show you everything you need to change. You may be surprised though. ;)

I thought the Vector data structure was old, but I could be wrong. If there is a solution that could be done in ArrayList or Vector form, I would probably choose ArrayList.

Vector is indeed old. It is kept around mainly for legacy reasons (backwards compatibility with old code) and its use it not advised in new applications.

Sadly many tutorials and beginners' books were written ages ago and only minimally updated to keep track of new developments and thus still use Vector, thus leading many people who start out in Java to learn to use something they really shouldn't.

I've been wondering for some time now why Sun didn't just deprecate Vector, which would cause compiler warnings to be thrown whenever it's used (thus deterring people away from Vector).

ArrayList is the most common replacement, though other Lists exist (such as LinkedList) for specific scenarios.
It's faster (because it's not synchronized) and fully implements the List interface (something recently backfitted to Vector as well).
Even when needing synchronization, ArrayList (in its synchronized form) should be preferred over Vector.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.