ArrayList v/s Vector

Which is more beneficial to use?
ArrayList or a Vector?
Both are dynamic arrays,so which is more
preferable to use?
Can anyone help please?

The Performance of Java's Lists
Vector or ArrayList -- which is better?

Similar Messages

  • Why Arraylist better than vector?

    Hi,
    Why Arraylist better than vector?.....i heared about it that fast then vector......how it's possible ?.....how can we find out....?

    ArrayList is faster then vector.because in vector class all the methods are synchronized.so it is obvoiusly slow.Not everything that appears obvious is actually true.
    add more object into Arraylist and vector say(1000).we have a method called currentTimeMillis() in System class .
    use that and try to iterate both (arraylist,vector) objectIf you had ever done this test (use 100000 rather than 1000 as the resolution of currentTimeMillis() is too course), then you would know that Vector is faster more often than not:new List()      new List(N)
    Add+Iterate     Add+Iterate     Add Only        Iterate Only
    ArList  Vector  ArList  Vector  ArList  Vector  ArList  Vector
    609     516     250     250     63      94      109     125
    562     516     250     266     78      94      125     109
    609     500     266     250     78      93      141     110
    532     547     250     265     62      93      110     125
    547     500     250     265     78      94      125     109
    547     500     266     265     62      94      109     109
    547     500     250     281     78      78      125     109
    ms averaged over 7 runs:
    565     511     255     263     71      91      121     114
    jdk 1.4.2_07 Windows client
    N = 1000000 The vector wins when you don't know the size it's going to end up (its capacity increases by 2 rather than 1.5 each time it grows, so there are fewer array allocations). There's no significant difference between the two on iteration. It is only when you are adding to a Vector that already has sufficient capacity that there's a measurable difference.
    Anything that requires contension on the locks will probably adversely affect the Vector's performance.
    Pete

  • ArrayList   Vs LInked List    Vs   Vector

    Which is one is faster -ArrayList ,LInked List ,Vector
    Thank you

    arun240 wrote:
    Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.Mostly right, but:
    - adding elements to the end of an ArrayList is pretty fast as well.
    - removing elements from the end of an ArrayList is pretty fast
    - occasionally adding an element to an ArrayList can trigger a resize of the internal array which makes it a bit slow-ish, but this evens out over time
    - get() for elements at the very beginning or end (or very near that) is reasonably fast for LinkedList as well
    - deleting from a LinkedList at a random position using an Iterator is pretty fast
    - deleting from a LinkedList at a random position using remove(int) is pretty slow, as it first needs to do the equivalent of get(int), which is slow
    The moral of the story: learn your data structures well, even if it's boring. It has many implications.
    And we're not even going into HashMap/Queue/Heap territory here.

  • ArrayList = Vector  | ArrayList Vector | ArrayList == Vector

    I want to know when we should use ArrayList instead of Vector, or vice-versa. I know that Vector is synchronized and ArrayList is not. But someone said that ArrayList is faster. This case also happens with Hashtable and HashMap.
    Can anybody help me?

    In new code, use ArrayList unless you are using something in Swing (or anything else) that was defined to require a Vector (done that way because Vector was the only thing around at the time, I think). If you want a synchronized List, use:
    List myList = Collections.synchronizedList(new ArrayList());Same for Hashtable/HashMap
    Map myMap = Collections.synchronizedMap(new HashMap());

  • Retrieving datas with ArrayList

    Below, im trying to get 6 columned records from the access database.
    //PNL 1:
                                  PNL1=new JPanel();
                                  PNL1.setLayout(new BorderLayout(15,15));
                                                    java.awt.List veri;
                                                    ArrayList veri2;
                                  lblABaslik=new JLabel("Arama Sonuclari :");
                                  String[] sutunAdlari={"Tarih","Arac","Kategori","Aciklama","Detay","Miktar"};
                                  int sayac=-1;
                                  java.util.Date tarih;int arac;int kategori;int aciklama;String detay;int tutar;
                                       try {
                                            String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=..\\bekir.mdb";
                                            String query="select * from harcamalar where tarih between # 2003-11-14 # and #2003-12-14 #";
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection con=DriverManager.getConnection(url,"serdar","serdar");
                                            Statement stmt=con.createStatement();
                                            ResultSet rs = stmt.executeQuery(query);
                                                                     veri=new java.awt.List(6);
                                                                     veri2=new ArrayList();
                                                                     String ekle;
                                                                     while(rs.next()) {
                                                                       ekle=new String(rs.getString("tarih"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("arac_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("kategori_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("aciklama_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("detay"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("miktar"));
                                                                           veri.add(ekle);
                                                                     veri2.add(veri);
                                            rs.close();
                                            stmt.close();
                                            con.close();
                                       catch (ClassNotFoundException e2){
                                            e2.printStackTrace(System.err);
                                       catch (SQLException e2){
                                       System.err.println("SQL state: " + e2.getSQLState());
                                       System.err.println("SQL error: " + e2.getErrorCode());
                                       e2.printStackTrace(System.err);
                                                    table=new JTable(veri2,sutunAdlari);
                                  table.setPreferredScrollableViewportSize(new Dimension(600,100));
                                  JScrollPane scrollpane=new JScrollPane(table);
                                  PNL1.add("North",lblABaslik);
                                  PNL1.add("Center",scrollpane);
                                  table.addMouseListener(new MouseAdapter() {
                                       public void mouseClicked(MouseEvent e) {
                                            System.out.println(table.getSelectedRow());
    but i get the error :
    "BekirAna2.java": cannot resolve symbol: constructor JTable (java.util.ArrayList,java.lang.String[])in class javax.swing.JTable at line 1928, column 55
    which represents the line :
    table=new JTable(veri2,sutunAdlari);
    thanx

    i changed the codes with Vector definitions;
                             //PNL1 :
                                  PNL1=new JPanel();
                                  PNL1.setLayout(new BorderLayout(15,15));
                                                     Vector veri;
                                                     Vector veri2;
                                                     //ArrayList veri2;
                                  lblABaslik=new JLabel("Arama Sonuclari :");
                                  //Object[][] veri=new Object[10][7];
                                  //veri[0][0] = new String("foo"); //etc.
                                  String[] sutunAdlari={"Tarih","Arac","Kategori","Aciklama","Detay","Miktar"};
                                  int sayac=-1;
                                  java.util.Date tarih;int arac;int kategori;int aciklama;String detay;int tutar;
                                       try {
                                            String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=..\\bekir.mdb";
                                            //String query="select * from harcamalar";
                                            String query="select * from harcamalar where tarih between # 2003-11-14 # and #2003-12-14 #";
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection con=DriverManager.getConnection(url,"serdar","serdar");
                                            Statement stmt=con.createStatement();
                                            ResultSet rs = stmt.executeQuery(query);
                                                                     veri=new Vector();
                                                                     //veri2=new ArrayList();
                                                                     veri2 = new Vector();
                                                                     String ekle;
                                                                     while(rs.next()) {
                                                                       ekle=new String(rs.getString("tarih"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("arac_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("kategori_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("aciklama_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("detay"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("miktar"));
                                                                           veri.add(ekle);
                                                                     veri2.add(veri);
                                            rs.close();
                                            stmt.close();
                                            con.close();
                                       catch (ClassNotFoundException e2){
                                            e2.printStackTrace(System.err);
                                       catch (SQLException e2){
                                       System.err.println("SQL state: " + e2.getSQLState());
                                       System.err.println("SQL error: " + e2.getErrorCode());
                                       e2.printStackTrace(System.err);
                                  //table=new JTable(veri,sutunAdlari);
                                                    table=new JTable(veri2,sutunAdlari);
                                  table.setPreferredScrollableViewportSize(new Dimension(600,100));
                                  JScrollPane scrollpane=new JScrollPane(table);
                                  PNL1.add("North",lblABaslik);
                                  PNL1.add("Center",scrollpane);
                                  table.addMouseListener(new MouseAdapter() {
                                       public void mouseClicked(MouseEvent e) {
                                            System.out.println(table.getSelectedRow());
                                  });but i still get the error alike:
    "BekirAna2.java": cannot resolve symbol: constructor JTable (java.util.Vector,java.lang.String[])in class javax.swing.JTable at line 1931, column 55
    pointing the line;
    table=new JTable(veri2,sutunAdlari);

  • A problem with ArrayLists

    Hello
    I'm pretty new to Java, and sometimes all those objects, instances, classes, data types etc confuse me. I'm having some kind of a problem with ArrayLists (tried with vectors too, didn't work) . I'm writing a program which takes float numbers from user input and does stuff to them. No syntax error in my code, but I get a java.lang.ClassCastException when I run it.
    I insert stuff to the ArrayList like this:
    luku.add(new Float(syotettyLuku));no problem
    I'm trying to access information from the list like this inside a while loop
    float lukui = new Float((String)luku.get(i)) .floatValue();but the exception comes when the programme hits that line, no matter which value i has.
    Tried this too, said that types are incompatible:
    float lukui = ((float)luku.get(i)) .floatValue();What am I doing wrong? I couldn't find any good tutorials about using lists, so i'm really lost here.
    I'll post the whole code here, if it helps. Sorry about the Finnish variable and method names, but you get the idea :)
    package esa;
    import java.io.*;
    import java.util.*;
    public class Esa {
    static final int maxLukuja = 100;
    static BufferedReader syote = new BufferedReader(new InputStreamReader(System.in));
    static String rivi;
    static String lopetuskasky = "exit";
    static double keskiarvo;
    static ArrayList luku = new ArrayList();
    static int lukuja;
    static float summa = 0;
    // M��ritell��n pari metodia, joiden avulla voidaan tarkastaa onko tarkasteltava muuttuja liukuluku
    static Float formatFloat(String rivi) {
        if (rivi == null) {
            return null;
        try {
            return new Float(rivi);
        catch(NumberFormatException e) {
            return null;
    static boolean isFloat(String rivi) {
        return (formatFloat(rivi) != null);
    // Luetaan luvut k�ytt�j�lt� ja tallnnetaan ne luku-taulukkoon
    static void lueLuvut() throws IOException{
        int i = 0;
        float syotettyLuku;
        while(i < maxLukuja) {
            System.out.println("Anna luku kerrallaan ja paina enter. Kun halaut lopettaa, n�pp�ile exit");
            rivi = syote.readLine();
            boolean onkoLiukuluku = isFloat(rivi);
            if (onkoLiukuluku) {
                syotettyLuku = Float.parseFloat(rivi);
                if (syotettyLuku == 0) {
                    lukuja = luku.size();              
                    break;
                }  // if syotettyluku
                else {
                    luku.add(new Float(syotettyLuku));
                    i++;
                } // else
            } // if onkoLiukuluku
            else {
               System.out.println("Antamasi luku ei ole oikeaa muotoa, yrit� uudelleen.");
               System.out.println("");
            } // else
        } // while i < maxlukuja
    // lueLuvut
    static void laskeKeskiarvo() {
        int i = 0;
        while(i < lukuja) {
            float lukui = ((float)luku.get(i)) .floatValue();
            System.out.println(lukui);
            summa = summa + lukui;
        }   i++;
        keskiarvo = (summa / lukuja);
    } // laskeKeskiarvo
    public static void main(String args[]) throws IOException {
    lueLuvut();
    laskeKeskiarvo();
    } // main
    } // class

    Thanks! Now it's functioning.
    As I mentioned, I tried this:
    float lukui = ((float)luku.get(i))
    .floatValue();And your reply was:
    float lukui =
    ((Float)luku.get(i)).floatValue So the problem really was the spelling, it should
    have been Float with a capital F.
    From what I understand, Float refers to the Float
    class, Correct. And float refers to the float primitive type. Objects and primitives are not interchangeable. You need to take explicit steps to convert between them. Although, in 1.5/5.0, autoboxing/unboxing hide some of this for you.
    so why isn't just a regular float datatype
    doing the job here, like with the variable lukui?Not entirely sure what you're asking.
    Collections take objects, not primitives, and since you put an object in, you get an object out. You then have to take the extra step to get a primitive representation of that object. You can't just cast between objects and primitives.
    Again, autoboxing will relieve some of this drudgery. I haven't used it myself yet, so I can't comment on how good or bad it is.

  • Passing a Vector object as a parameter to a method

    Hi,
    How can I pass a Vector object as a parameter to a method?
      void buttonAdd_actionPerformed(ActionEvent e) {
        Vector studentHobbies = new Vector();
          String[] items = listHobbies.getSelectedItems();
          for (int i=0; i<items.length; i++) {
            studentHobbies.addElement(items);
    newStudent = new Student(Name,StudentNumber,studentHobbies);
    studentenlist.addTo(newStudent);
    So I want to pass the Vector object 'studentHobbies'  to a method.
    Would I do something like this :import java.util.Vector;
    public Student(String Name, int StudentenNumber, Vector studentHobbies){
    this.Name = Name;
    this.StudentNumber = StudentNumber;
    this.studentHobbies = StudentenHobbies;

    yes, thats how you do it.
    maybe you should first try your idea and then ask people questions?
    also, use ArrayList instead of Vector, its better - google as to why if you care.

  • Two Dimensional Vector ?

    Hya,
    Is it possible to have two dimensional Vectors ?
    if yes, how would be declared ?
    I have a class called pencil,
    I want to put each 12 pencils in 1 Vector (pencil box)
    then add each of those vectors into a vector (box of pencil boxes)
    thanks in advance

    There's not really any such thing as a 2D vector
    (unless you create such a class) but you can create a
    Vector of Vectors. You can just add pencils to
    vector and add that vector to another vector.
    You might want to consider creating a PencilBox
    class, rather than using a Vector to hold the
    pencils.
    You should also use ArrayList rather than Vector.When should an arrayList be used ? or when should a Vector be used?
    thanks

  • Replacing vectors with better collection

    Hi,
    My Netbeans IDE is giving me a hint that vectors (which I am using to build custom table models from AbstractTableModel) are obsolete.
    What should I replace vectors with, or what collection should I use to build custom table models, any example will be appreciated.
    Thanks

    jverd wrote:
    Use ArrayList instead of Vector.
    However, interaction with legacy GUI APIs is one commons place where you have to use Vector. I'm not sure if AbstractTableModel falls into that category, but you can find out easily enough.Unlike DefaultTableModel, AbstractTableModel makes no assumptions about how the data must be stored. That is why it is useful. It can be used to adapt other data structures to TableModel without the need to copy the data.

  • How to change the value of a two dimensional vector

    hi,
    I have a two dimensional array, Vector<Vector> myData, which contains strings. It's size is 5 rows and 6 columns
    I would like to change the value of, say, row 3, colum 5 from whatever it contains now to "new data"? I have searched and searched, but no luck
    thanks

    micheleg wrote:
    hi,
    I have a two dimensional array, Vector<Vector> myData, which contains strings. It's size is 5 rows and 6 columns
    I would like to change the value of, say, row 3, colum 5 from whatever it contains now to "new data"? I have searched and searched, but no luck
    thanksFirst off, you do not have an array of any dimension.You have a Vector that contains Vectors that contain Objects (you should provide a more specific type in your declaration).
    To change the element at position x in the y'th Vector, get the y'th Vector and change the x'th element in said Vector.
    As a side note, you should be using ArrayList instead of Vector these days.

  • Does vector reduces performance

    Hi,
    it is said that vector is serializable and thread safe
    so it is slow
    ny doubt is if we declare and use vector in a local method then it is not shared with others does still the fact that vector is serializable reduces performance
    is using arraylist better
    i have seen code of many people using vectors
    if vectors are not to be used we have to be careful
    about vectors is using arraylist better than vector
    for same functionality or which is better to use
    if requirement is to store string array which can
    extend to any number of items

    Hi,
    Vectors are extremely slow, due to it being synchronized. An ArrayList is a lot faster than a Vector, but if possible, I'd look at just a plain old array. Arrays are extremely faster than both ArrayList or a Vector. The problem is that arrays don't automatically resize. So it really depends on your design. If you do end up going with a Vector, don't use an Enumeration of Iterator to iterate over the Vector. A lot of unnecessary objects are created, etc... Get the size of the vector at use a simple loop, which is more compact and quicker....
    /rick

  • Vector did not retrun the correct values.

    in my class the vector use BigDecimal not bigInteger. but my problem now is that my vector retruns the first value stored in vector until the loop completed.
    the following is print statment while I add to the vector:
    while (rs.next())
         CustNum=rs.getBigDecimal("CustNum");
         CType = rs.getString("TYPE");
         row.addElement(CustNum);
         row.addElement(CType);
         ret.addElement(row);
         System.out.println(CustNum);
    ***********1119
    ***********2220
    ***********3331
    but in my JSP:
    Vector v = new getNumber().getCustNumber();
    Iterator i = v.iterator();
    while (i.hasNext()) {
    Vector row = (Vector)i.next();
    Object CustNum = row.get(0);
    Object name = row.get(1);
    system.out.println(CustNum);
    that retrun the wrong result:
    ***********1119
    ***********1119
    ***********1119

    As warnerja said, you apparently only have multiple references to the same 'row' in your 'ret' Vector.
    If your code in your post is exactly your actual code, then you are adding the same Vector to 'ret' multiple times. That Vector will have two values (CustNum and CType) for each row.
    So, your 'ret' will have three elements, each with six elements (I separated the elements with commas):
    ret.get(0):   ******1119, Type1, ******2220, Type2, ******3331, Type1
    ret.get(1):   ******1119, Type1, ******2220, Type2, ******3331, Type1
    ret.get(2):   ******1119, Type1, ******2220, Type2, ******3331, Type1Each element of 'ret' is identical--you have three copies of the same Vector.
    In your loop to populate 'ret', initialize 'row' to a new Vector at the beginning of each loop iteration. Also, you may want to try using ArrayList instead of Vector. You probably don't need the synchronization that Vector gives. Even if you do need synchronization, use Collections.synchronizedList(new ArrayList()).

  • Vector format help!

    in an array i could do this:
    public class items
      String label;
      int qty;
      double price;
    public static void main(String[]args)
    items[] i = new items[1];
    items[0] = new items();
    items[0].label = watta;
    items[0].qty = 1;
    items[0].price = 4.5;
    }but how about on vectors? how can i format a vector slot to contain the class items at the same time?

    Your main method is wrong. It's better to create an object, set it's properties, then add it to a collection. Also, you're referencing the class name, not the array variable.
    public static void main(String[]args) {
        items anItem = new items();
        anItem.label = watta;
        anItem.qty = 1;
        anItem.price = 4.5;
        items[] itemsArray = new items[1];
        itemsArray[1] = anItem;
    }Use ArrayList instead of Vector. Read the Collections tutorial: http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html

  • Is there any default size for ArrayList

    The default capacity of Vector is 10.
    Is there any default size for ArrayList ??
    Vector v = new Vector();
    System.out.println("==> "+v.capacity()); // output is ==> 10
    java.util.List alist = new ArrayList();
    System.out.println("==> "+v.capacity()); // here the out put is ==> 0
    Regards
    Dhinesh

    No default size for arraylist.initially it's zero.
    I think u r comparing capacity with a size those two are different.
    Size- represents number of elements in the array.
    capacity- the capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
    it depends on the ensureCapacity() method in the arraylist.

  • Vectors shapes dissapear or group elements are mooved to another coordinates

    A month ago, I experiment some bugs on fireworks. There are shapes, that dissapear, or group elements thah disappear and when you try to select his layer, the shape appears in another coordiantes, and it's impossible to select. Mask boxes change you height by 1px and it's impossible to modify. The rounded shapes are deformed, like someone move the paths to the right.
    I have a lot of desings mades with fireworks, and many files become corrupt, with this case of bugs that I've mentioned at the beginning.
    A friend that also have fireworks has proved the same file, and it is perfect, but if I open the file, happens all this thing that explain on top.
    What is happening?@

    1.) forget "Vector" if you're talking about (modern) Java Code. You most likely want to use a implementation of List instead (usually ArrayList or LinkedList), Vector is a legacy class and should usually not be used in new code.
    2.) You could keep everything in XML all the time, for this you would use the DOM tree of your document. In my opinion that's usually too much hassle, as you'd have to convert each data access.
    3.) Do you mean to use the list to store the objects or the properties of the objects?
    4.) A standalone application is no reason not to use a database. HSQLDB provides almost everything you need from a database without having to install anything. Of course a XML file might still be the better idea, but you should think about it.
    Good Luck

Maybe you are looking for

  • Loss Of Sound Sync - FC7

    Hi Gang Working with FC7 in Snow Leopard 10.6.8 and an older Mac Pro. Exported a 70 minute clip and noticed loss of Sound Sync, (about mid way thru in a QT File). The clip is a mixture of assorted clips. Divided the 70 minute clip into 3 separate exp

  • How to contact the author of an application on the iPhone AppStore?

    Is there a link on the iPhone AppStore to send questions or suggestions to the developer of an application? (If not, why isn't there one? )

  • How can i use C/Javascript/php/Java in flex?

    can i embed these language into my flex project? since i have to check harddisk space, free memory remain. Also, i need to check the pixel of photos before the photos becoming bitmapdata please help~

  • Question on using table types in methods

    Hi    I have a simple question involving passing table types in method I want to pass an internal table by reference - to a method and within the method populate the internal table (t1) using a select * into the internal table and then sort t1 by f1

  • Banded profile after line trouble after 3 days

    Hi, I had some line trouble over a week ago and needed a BT engineer to come and fix the dead line. This was duly sorted and I found when I connected for the first time after this my down speed was 288Kbps and up was 1024Kbps which I understand is a