Vectors VS Arrays VS LinkedLists

Hi
I am basically looking for some info on the advantages or disadvantages of using any of the above. I would like to know how one justifies the use of one over the other.
I would be grateful for any pointers or resources you could point me to.
Cheers

Use arrays if you know the size you will need, you won't be inserting or removing elements and you need highly efficient indexed access to the elements.
Use ArrayList if you don't know how large to make the container, you need efficient indexed access to the elements, you don't need to have efficient insertion or removal of elements from the interior of the container and you don't need thread safety on the individual operations (the most common case).
Use Vector or a synchronized ArrayList is your needs are like those for ArrayList but you need thread safety of the individual operations.
Use LinkedList if you don't need efficient indexed access but you do need efficient insertion and removal of elements from the interior of the container and you don't need thread safety of individual operations (the usual case).
Use the synchronized wrapper of LinkedList if your needs are like those that lead you to LinkedList but you need thread safe individual operations.
I am sure this is documented better someplace else, but I haven't taken the time to check.
Chuck

Similar Messages

  • Array of linkedlist of object - help! plesse!

    I am writing an array of linkedlist and the elements of the linkedlist is an object carrying 2 interger. It didn't compile and the message is as follows:
    C:\thesis5>javac testLL2.java
    testLL2.java:22: cannot resolve symbol
    symbol : variable vertexFanObj2
    location: class testLL2
    vertexFanObj2 = myLL2[ i].get(j);
    ^
    1 error
    My program is as follows:
    import java.net.*;
    import java.io.*;
    import java.util.LinkedList;
    public class testLL2 {
    public static void main(String[] args) throws IOException {
    int myLLLength;
    Integer intObj;
    LinkedList myLL2 [] = new LinkedList[10];
    vertexFan vertexFanObj;
    for (int i = 0; i < 10; i++) {
    myLL2[ i] = new LinkedList();
    for (int j=0; j < 5; j++) {
    vertexFanObj = new vertexFan();
              vertexFanObj.setupVertex(j, -j);
    myLL2.add(vertexFanObj);
    for (int i = 0; i < 10; i++) {
    myLLLength = myLL2[ i].size();
    for (int j=0; j<myLLLength; j++) {
    vertexFanObj2 = myLL2[ i].get(j);
    System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
    class vertexFan {
    int vertex1, vertex2;
    void setupVertex(int vertexA, int vertexB) {
    vertex1=vertexA;
    vertex2=vertexB;
    I 've got lost! Please kindly help you! Many thanks in advance!

    for (int i = 0; i < 10; i++) {
    myLL2[ i] = new LinkedList();
    for (int j=0; j < 5; j++) {
    vertexFanObj = new vertexFan();
    vertexFanObj.setupVertex(j, -j);
    myLL2.add(vertexFanObj);
    for (int i = 0; i < 10; i++) {
    myLLLength = myLL2[ i].size();
    for (int j=0; j<myLLLength; j++) {
    vertexFanObj2 = myLL2[ i].get(j);
    System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
    } Its a scope issue.
    You define vertexFanObj in a for loop. then try to access it from outside that for loop. (in another for loop)
    for (int i = 0; i < 10; i++) {
    myLL2[ i] = new LinkedList();
    vertexFanObj = new vertexFan(); //I MOVED THIS LINE
    for (int j=0; j < 5; j++) {
    vertexFanObj.setupVertex(j, -j);
    myLL2.add(vertexFanObj);
    for (int i = 0; i < 10; i++) {
    myLLLength = myLL2[ i].size();
    for (int j=0; j<myLLLength; j++) {
    vertexFanObj2 = myLL2[ i].get(j);
    System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
    } should work properly...

  • Challeging Traversal of Vector and Array

    Hi there ! I would like to render the values of this Vector and Array . How do I print it out to the browser ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while (rset.next())
    aRow = new String[numColumns];
    for (int i=0; i < numColumns; i++){
    aRow[i] = rset.getString(i+1);
    allRows.addElement(aRow);
    return allRows;
    }

    Hi there !
    Thanks for your help but I managed to get it working. For references purposes, I`ll post it here.
    My problem now is this :-
    How can I issue another SQL statement and store the results in the same array?
    Pls note . One Sql per table so, that`s the issue ?
    Can someone help with a followup code ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while(rset.next())
    // for every record instance aRow
    aRow = new String[numColumns];
    // store in aRow the values of the record
    for(int i=0;i<numColumns;i++)
    aRow[i] = rset.getString(i+1);
    //When aRow is full store it in the vector
    allRows.addElement(aRow);
    // when the rset finished print all the Vector
    for(int i=0;i<allRows.size();i++)
    // get returns a String[]
    String[] tmpRow = (String[])allRows.get(i);
    for(int j=0;j<tmpRow.length;j++)
    out.print(tmpRow[j]+" ");
    out.println("");
    }

  • WHY WE USE VECTOR NOT ARRAY STRING

    Hi
    I want to know why we use Vector not bufferstring.
    What is the difference Vector(1,1) and STRING[1][1]?
    Which one we will prefer?
    Why we will prefer one of them?
    Please help me to find out.

    There are huge differences between array and Vector.
    Array is a special class that allows to keep references to a number of Objects of some type. It has a maximum length set during construction, and does not offer any methods to change it's size (without defining a new array).
    Vector is a class (thread-safe unlike it's new version ArrayList) that allows to keep references to any Object (may be of different types). It doesn't have a maximum length set, and can be potentionally of any size. It allows to easily remove, add, insert new elements and keeps all the elements in the order they were added (unless some object was inserted). This is a really well written class, and I'm always using it for storing some objects.
    Hope it was helpful.

  • NullPointerException with an array of LinkedList

    Hello Everybody.
    I'm new to Java and I am trying to use a quite complicated data structure but I am missing something since it does not work.
    Here comes my code:
    import java.util.LinkedList;
    class ObjectToHold {
    public int i;
    ObjectToHold (int j) {
    i=j;
    public class ModifiedArray {
    static final int ARRAY_DIMENSION = 79;
    private LinkedList[] myInternalArray;
    ModifiedArray() {
    LinkedList[] myInternalArray = new LinkedList[ARRAY_DIMENSION];
    for (int i=0;i<ARRAY_DIMENSION;i++) {
    myInternalArray[i] = new LinkedList();
    void insert (int slot, ObjectToHold a) {
    ((LinkedList)myInternalArray[slot]).addLast(a);
    public static void main(String[] args) {
    ModifiedArray myModifiedArray = new ModifiedArray();
    for (int j=0; j<ARRAY_DIMENSION;j++) {
    myModifiedArray.insert(j,new ObjectToHold(j));
    The class ModifiedArray contains a private array of LinkedList objects. I wrote an "insert" method to put objects of type ObjectToHold (which is a very simple one!) into the array.
    While compiling the code, everything works fine.
    On the other hand, when I run the compiled code I get the following run time Exception:
    Java.lang.NullPointerException
    at ModifiedArray.insert ....
    Modified.Array.main ...
    The problem must be in the way I use the reference to myInternalArray.
    I also tried
    myInternalArray[slot].addLast(a);
    instead of
    ((LinkedList)myInternalArray[slot]).addLast(a);
    but I got the same result.
    Can anybody help me or do I have to ask in some other forum?
    Thank you very much
    Tommaso

    You defined myInternalArray as local to the constructor as well as an instance variable.
    Try..
    import java.util.LinkedList;
    class ObjectToHold {
      public int i;
      ObjectToHold (int j) {
        i=j;
    public class ModifiedArray {
      static final int ARRAY_DIMENSION = 79;
      private LinkedList[] myInternalArray;
      ModifiedArray() {
        myInternalArray = new LinkedList[ARRAY_DIMENSION];
        for (int j=0; j<ARRAY_DIMENSION; j++) {
          myInternalArray[j] = new LinkedList();
      void insert (int slot, ObjectToHold a) {
        ((LinkedList)myInternalArray[slot]).addLast(a);
      public static void main(String[] args) {
        ModifiedArray myModifiedArray = new ModifiedArray();
        for (int j=0; j<ARRAY_DIMENSION;j++) {
          myModifiedArray.insert(j,new ObjectToHold(j));
    }

  • Vectors, lists, arrays

    Hi, I'm writing a program using a variable length sequence of boolean values. I will want to manipulate this, altering & reading etc and don't know what will be most time efficient (prog has lots of iterations and takes a while). Any ideas what'd be best for this, vectors, lists, arrays or something else?
    Cheers

    There should be no difference.
    For using List or any Collection interface, you need to use Boolean, the object though.
    You can simplify the storage by just using boolean[], the array, but with "variable length", you have to deal with growing the array. So List is simpler overall.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • [svn:osmf:] 11069: Minor API change: Use Vector not Array for MediaElement. get traitTypes.

    Revision: 11069
    Author:   [email protected]
    Date:     2009-10-21 16:52:10 -0700 (Wed, 21 Oct 2009)
    Log Message:
    Minor API change: Use Vector not Array for MediaElement.get traitTypes.  Approved by dev team. Should be no impact to sample apps, unit tests, or test apps.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/media/MediaElement.as
        osmf/trunk/framework/MediaFramework/org/osmf/proxies/ProxyElement.as

    Revision: 11069
    Author:   [email protected]
    Date:     2009-10-21 16:52:10 -0700 (Wed, 21 Oct 2009)
    Log Message:
    Minor API change: Use Vector not Array for MediaElement.get traitTypes.  Approved by dev team. Should be no impact to sample apps, unit tests, or test apps.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/media/MediaElement.as
        osmf/trunk/framework/MediaFramework/org/osmf/proxies/ProxyElement.as

  • Vector vs Array performance?

    Hi, I've heard some ppl says that Vector is slower than Array. Does anyone know what's the different in speed between using an array and a vector?
    Say with the same algorithm, the one uses array take 10s for 1mil iteration, how long with it take for vector?
    Thanks...

    For what it's worth adding 10K strings to various collections and accumulating 1000 results, this is what I saw:
    Vector() 0.69/0.53:
    ArrayList() 0.84/0.69:
    HashSet() 2.15/0.36:
    Vector(SZ) 0.70/0.53:
    ArrayList(SZ) 0.25/0.43:
    HashSet(SZ) 1.56/0.52:
    LinkedList() 0.86/0.60:
    A slight win to Vector unless the collections have their initial size set, in which case ArrayList comes out ahead.
    Things are a little bit different using 500K strings and doing fewer runs (in both cases I didn't time the first two runs):
    Vector() 46.20/7.77: 50 38 49 38 50 63 49 38 49 38
    ArrayList() 51.60/6.00: 50 48 51 47 51 69 52 49 51 48
    HashSet() 662.30/31.28: 648 652 652 651 652 756 652 653 652 655
    Vector(SZ) 14.90/0.30: 15 14 15 15 15 15 15 15 15 15
    ArrayList(SZ) 33.20/7.21: 26 41 26 40 26 41 26 40 26 40
    HashSet(SZ) 520.30/1.73: 523 519 520 518 519 521 519 523 522 519
    LinkedList() 345.90/31.44: 336 339 332 336 440 336 334 337 332 337
    If the initial capacity is set Vector was a clear winner for collectons of this size.
    Edited by: pbrockway2 on Jan 10, 2008 11:16 AM
    I have no fscking idea why Vector should appear to get slower when the initial size is set to 10K. But, there you are.

  • Problem in converting vector to array of strings

    hi
    i am having a vector which in turn contains hashtable as elements
    Vector v=new Vector()
    Hashtable ht=new Hashtable();
    v.add(ht.add("key1",value1))
    v.add(ht.add("key2",value2))
    v.add(ht.add("key3",value3))
    v.add(ht.add("key4",value4))now i am trying to conver this vector in to a array of string like
    String[] str=(String[])v.toArray(new String[v.size()]);but i am getting java.lang.ArrayStoreExceptioncan anybody help me plz
    Thanks

    Hi,
    The api for public Object[] toArray(Object[] a) says
    Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.
    ArrayStoreException will be thrown if the runtime type of a is not a supertype of the runtime type of every element in this Vector.
    The runtime type of the elements of the vector is Hashtable.
    Because String is not a supertype of Hashtable the ArrayStoreException is thrown.

  • Newbie question about using vectors and arrays

    I'm fairly new to JME development and java in general. I need some help in regards to Vectors and 1 dimensional arrays. I'm developing a blackberry midlet and am saving the queried info i pull back from my server side application with each record saved into the array and subsequently each array saved as an element in the vector, thereby creating a 2D "array".
    However I'm having a problem accessing the elements in the array. Here is a sample of what I mean and where I get stuck:
    Vector _dataTable = new Vector(1, 1);
    String[] r1 = {"a", "b", "c", "d"};
    String[] r2 = {"1", "2", "3", "4"};
    _dataTable.addElement(r1);
    _dataTable.addElement(r2);
    Object temp = _dataTable.elementAt(0); //Save the element as an new object for useNow how do I access the particular indexes of the element of the temp object? Do i need to caste it to an array? Is there another more efficient/easier way I should be storing my data? Any help would be great!
    Edited by: Sotnem2k1 on Apr 1, 2008 7:50 AM
    Edited by: Sotnem2k1 on Apr 1, 2008 7:51 AM

    Thanks for the feedback newark. I have this scenario below:
    // Class for my 1D array
    public class OneRecord {
        private String[] elementData = new String[4];
        public OneRecord() {   
            elementData[0] = null;
            elementData[1] = null;
            elementData[2] = null;
            elementData[3] = null;
        public OneRecord(String v1, String v2, String v3, String v4) {   
            elementData[0] = v1;
            elementData[1] = v2;
            elementData[2] = v3;
            elementData[3] = v4;
        public void setElement(int index, String Data) {
            elementData[index] = Data;
        public String getElement(int index) {
            return elementData[index];
    } Then in my main app I have:
    Vector _dataTable = new Vector(1, 1);
    OneRecord currRecord = new OneRecord("a", "b", "c", "d");
    _dataTable.addElement(currRecord);
    OneRecord temp = (OneRecord)_dataTable.elementAt(1);
    System.out.println(temp.getElement(0)); Are there more efficient data structures out there to save queried data from a server side app? Like I said, i'm still trying to learn the most efficient techniques of coding...esp for the Blackberry. Any suggestions would be great!

  • Copy the values of Vector to Array

    hi all,
    I have one problem that is
    I have one vector that holding objects (Ovalue)
    and Ovalue has the x,y values....
    I would like to copy the x,y values to one array
    if anyone knowd please help me
    thanks..

    Vectors have a toArray() function.

  • How do I get an array of LinkedLists?

    I need an array of liked lists
    I tryed the code:
    LinkedList buckets[] = new LinkedList[radix];But that generated an unchecked warning when I tried to put an Integer into it.
    I changed it to:
    LinkedList<Integer> buckets[] = new LinkedList<Integer>[radix];But that generated a "generic array creation" error.
    is it possible to to get an array of lists without warnings?

    It is possible to use generic arrays (simple ones)
    e.g.
    import java.util.List;
    public class Test
       public static void main(String[] args)
          String[] elements = new String[]{"Happy","Go","Lucky"};
          String middleElement = middleElement(elements);
          System.out.println(middleElement);
       public static <T> T middleElement(T[] elements)
          return elements[elements.length/2];
    }However you cannot (should not) create generic arrays with bounded parameters.
    Lets say that we have somehow create a generic array:
    List<String>[] lists = ...
    Then since lists is an array we can assign it to Object[]
    Object[] objArray = lists;
    and now we can put any list in the array.
    objArray[0] = new ArrayList<Rectangle>();
    Even though this should not happen, the runtime has no way to check aginst it and so no ArrayStoreException is thrown.
    You are however free to:
    List<?>[] lists = new List<?>[5];
    which implies its an array of any type of List.

  • Converting a Vector to array

    Hi,
    How can I convert a Vector to an array of int ?
    I tried this
    //v is an object of class Vector
    int [] res=(int [])v.toArray(new int[0]);but it doesn't work so I find another way:
    //v is a Vector
    int len=v.size();      
    int[] res=new int[len];         
    for (int count=0;count<len;count++)
    res[count]=Integer.valueOf(v.elementAt(count).toString());      this works but it's inefficient , I want to do the conversion in a single line of code (if possible)
    thanks

    The code that I've posted belongs to a simple function whose aim is to fill an array with
    all the prime numbers the are less than a given value.
    The function must return an array of int (int[]).Since I don't know how many primes I will find, I need a growable array, so I decided to use Vector.If there is a better way, please tell me.
    Here is the function prototype:
    /**returns all prime numbers that are less than max_value*/
    public int[] getPrimeNumbers(int max_value){
    //function's body
    }thank you in advance

  • Vector with array

    If a vector contains elements which are String[2], how do i get the array element?
    Vector group=new Vector();
    String info[]=new String[2];
    here assign info some value and add to group
    // now try to print them out
    Enumeration enu=group.elements();
    while (enu.hasMoreElements() ){
    // this does not work right here. Need some refreshment.
    String result[]=(String)enu.nextElement();
    // how do i print the info[0] and info[1]
    }

    You need to cast to a String[] rather than String:
    String result[] = (String[])enu.nextElement();
    System.out.println("Result is: " + result[0] + ", " + result[1]);This is one of the reasons that many people prefer to use the following syntax to define arrays:
    String[] info = new String[2];rather than
    String info[] = new String[2];It makes it clear that info is of type String[] rather than String.
    Anyway, hope this helps.

  • Vector or array

    Hi,
    I have a set of numbers say 1 to 1000 (Set A)
    I want to process them one at a time and as I process them, they will create another number which will also exist in the original set A.
    These numbers that exist in the set A, I want to remove and then continue to process the next number.
    I have at present been working around the problem by just using a simple for loop for the 1 to 1000 and storing the numbers that need to be removed in an array.
    Each step then requires me to check if the current no. in the for loop isnt in the array before processing.
    This seems very wasteful and not very fast. I was wondering what woud be the best approach.
    Robin

    A HashMap should be pretty good for answering the question "is a given number in this set".
    But before optimizing ask yourself: do you really need to? How long does the current program run? If the program is run a thousand times a day and the savings are significant then it may be worth it. If you are spending hours to save a couple of seconds from a program that gets used once a day - forget it and go spend the time at http://www.joecartoon.com/ instead.
    (joecartoon not necessarily work safe - contains audio.)

Maybe you are looking for

  • How to call the 'DETAIL' function in ALV for a program?

    Dear Friends, I have a prf_tree (TYPE REF TO cl_gui_alv_tree), and I added below codes to add an new button for displaying the detail record, it works fine: CALL METHOD prf_toolbar->add_button     EXPORTING       fcode     = prf_tree->mc_fc_detail   

  • Modeling

    Hi Can any one explain a complex scenario where we have to create custom cubes/ODS ...(when Business content has many useful ones). Thanks SAI

  • Cannot find any number on box that begins with 1057,  none of the other numbers work as a "serial number".

    cannot find any number on box that begins with 1057,  none of the other numbers work as a "serial number".

  • Why is it not running

    According to my knowledge i did everything right,yet it is not running.import javax.swing.JOptionPane; import java.io.*; public class file1 { static int[][] number=new int[1000][1000]; static int row,column;     public static void main(String[] args)

  • No audio realtek

    No audio coming out of speakers. Headphones still work but would appreciate both to work.  Have Realtek audio.  Was working up until the other day.