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.

Similar Messages

  • Linked list to string coercion doesn't use text item delimiters: bug?

    set AppleScript's text item delimiters to {"; "} -- well-known technique
    {1, -1, "c", "d"} as string -- curly braces specify a vector, delimiters work
    -- result: "1; -1; c; d"
    {1, -1, "c", "d"} as linked list as string -- if coerced to linked list, delimiters ignored
    -- result: "1-1cd"
    [1, -1, "c", "d"] as string -- square brackets specify a linked list, delimiters ignored
    -- result: "1-1cd"
    [1, -1, "c", "d"] as vector as string -- coercing linked list to vector first works
    -- result: "1; -1; c; d"

    Hello
    It appears that linked list to string coercion does not respect the AppleScript's text item delimiters which are set to list of Unicode text. (Unicode TIDs have no effects in coercion as if it were set to {""})
    I can confirm this behaviour in both AppleScript 1.8.3 (OS9) and 1.9.1 (OSX10.2.8) at hand.
    So it has been as such for a long time. Bug I'd call it.
    By the way, although this is not the point, linked list is a historical residue and of little use in real scripting. After all, it is much slower than vector with appropriate coding. So we may always coerce it to vector without losing anything.
    Regards,
    H
    Linked list to string coercion & AppleScript's text item delimiters (TIDs).
    When AppleScript's TIDs are set to list of Unicode text,
    the TIDs have no effect in coercion from linked list to string as if they were set to {""}.
    set aa to [1, 2, "a", "b"]
    --set aa to {1, 2, "a", "b"} as linked list
    set t1 to list2text(aa, ";") -- "1;2;a;b" -- in pre-AppleScript 2.0
    set t2 to list2text(aa, ";" as Unicode text) --"12ab"
    return {t1, t2}
    on list2text(aa, delim)
    list aa : source list
    string delim : a text item delimiter
    return string
    local astid, astid0, t
    set astid to a reference to AppleScript's text item delimiters
    set astid0 to astid's contents
    try
    set astid's contents to {delim}
    --set t to aa as string
    --set t to aa as Unicode text
    set t to "" & aa
    set astid's contents to astid0
    on error errs number errn
    set astid's contents to astid0
    error errs number errn
    end try
    return t
    end list2text

  • Why LinkedList uses doubly linked list and not single link list

    Hi,
    Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
    Edited by: user4933866 on Jun 26, 2012 11:22 AM
    Edited by: user4933866 on Jun 26, 2012 11:25 AM
    Edited by: EJP on 27/06/2012 08:50: corrected title to agree with question

    EJP wrote:
    Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again.

  • Create a linked list

    Hi guys!
    I read the manual of java 2 and says that is not that pointers don't exist, they do exist but they are not explicit as they are in C languagge. So in need to create a circular linked list how can I do this? The instructions of the manual are not so clear. Does anyone have an idea and can give me a sample code?
    Thanks to all
    Maddy

    References are like pointers except that you cannot make any add operation on them. But you can of course change their values to make it point to other objects.
    This also means that you can create graph objects and every data structure you like. For example :
    class BinaryNode {
        public Object data;
        public BinaryNode left;
        public BinaryNode right;
    }To create binary trees or
    class GraphNode {
        public Object data;
        public ArrayList links;
    }Where links is a Java list containing a list of links (references) to other GraphNode.
    Matthieu

  • Linked List and String Resources

    Linked Lists can be very slow when removing dynamic Strings.
    If you add and remove Strings in the
    following way, the performance is very poor:
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    - If you add and remove the not dynamic String: "" + 10000 instead,
    - or do not remove the String (but add it in the middle),
    - or use a ArrayList
    the performance is much better.
    I suppose it depends on handling the String resources.
    If you run the following class, you will see what I mean:
    public class SlowLinkedList
    public static void main (String[] args)
    // Be carefull when accessing/removing Strings in a Linked List.
    testLinkedList ();
    testLinkedListHardCodedString();
    testLinkedListNoRemove();
    testArrayList();
    testArrayListNoParam();
    private static void testLinkedList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time dynamic String remove " + time);
    private static void testLinkedListHardCodedString ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time same String remove " + time);
    private static void testLinkedListNoRemove ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add (i/2, "" + n);
    time = System.currentTimeMillis () - time;
    System.out.println ("time add dynamic String " + time);
    private static void testArrayList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList " + time);
    private static void testArrayListNoParam ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList ();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList same String " + time);
    A typic output of the Performance is:
    time dynamic String remove 1938
    time same String remove 312
    time add dynamic String 31
    time ArrayList 63
    time ArrayList same String 31

    begin long winded reply
    It doesn't matter if they are Strings or any other Object. LinkedList, in the way you are executing
    remove, is not effecient. The LinkList remove will look at the index, if it is less than the median
    it will start iterating from 0, if it is greater, it will start iterating in reverse from the end. Since you
    are removing from the median, it will always take the longest (either forward or backward) to
    get to the middle. Whereas, ArrayList simply uses the arraycopy to drop the element from the
    array. The "NoRemove" test doesn't make sense to me in relation to the others.
    Also, the VM is performing optimizations when you hardcode the 'n' value to 10000, it seems
    that the VM won't optimize when using 'n'. Tusing Integer.toString(n), instead of "" + n,
    in the first test case, it will yield better results.
    My profs in college drove collections into my head and removing from a linked list without
    an iterator is going to be inefficient. Iterators are a beautiful thing, use them.
    Try this code instead, it simulates your remove in the middle with an iterator and, on my
    machine, is faster than the ArrayList.
    private static void testLinkedList() {
        int n = 10000;
        long time = System.currentTimeMillis ();
        List list = new LinkedList();
        for (int i = 0 ; i < n ; i++) {
            list.add (Integer.toString(n));
        boolean forward = false;
        for (ListIterator li = list.listIterator(n >> 1); li.hasNext() || li.hasPrevious();) {
            if (forward) {
                li.next();
                forward = false;
            } else {
                li.previous();
                forward = true;
            li.remove();
        time = System.currentTimeMillis () - time;
        System.out.println ("time dynamic String remove " + time);
    }One other thing, run the tests more than once in a single VM and take the average. You could
    apply some statistical analysis to figure out which is better within a certain confidence percentage,
    but that is probably overkill. :)
    Check the collection tutorial for more info: http://java.sun.com/docs/books/tutorial/collections/implementations/general.html
    end long winded reply
    Matt

  • Sorting linked lists - Help

    I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
    My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
    thanks.

    Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
    Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
    (Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
    Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
    Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
    I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out.

  • Linked List mess

    Hello,
    I think I've gotten myself into a bit of a mess.
    I create a Linked List containing many strings. I do this for 10 separate tabs. I then want to combine Linked Lists into something else like a LinkedList again so I can then write that one combined list to a file. Something like an array but instead it takes in LinkedLists.
    The container of the 10 linked lists will never have more than 10 but will always have 10. If one of the tabs is not enabled I place a filler in for it. This is my code and it is throwing me a null pointer exception and I am sure it is because I initialize CETotalCover to null but I don't know how else I could initialize it. That leads me to believe this is probably not the right choice for what I am doing.
    LinkedList<String>[] CETotalCover = null;     
    LinkedList<String> noCover = new LinkedList();
    noCover.add("***");
    CEArray CEData = new CEArray();
    if (_Dailycover.isEnabled()){
         CETotalCover[0] = CEData.toLayer(_Dailycover.getRowData());
    else{
         CETotalCover[0] = noCover;
    }What would be the best way to do this? Sorry I'm new to Java and haven't had much experience with trying to make a list of lists.
    Edited by: Sch104 on May 19, 2008 10:25 AM
    Edited by: Sch104 on May 19, 2008 10:25 AM

    Correct, you never created an array object to store your lists in, so when you tried to access the first element it blew up. In order to fix that, you need to actually create the array. Unfortunately, generics and arrays do not play nicely together. Use an ArrayList instead.

  • Comparable linked list sorting

    i have been trying to find a way to sort a link listed. After some reading i found out that it is probably best to use collections.sort(list). I think i understand how to implement it , i need to declare a compareto and equals method. However, most of the reading i have done shows how to create a collection from a linked list and add items to the collection and sort them, however it doesn show how to copy this sorted collection back inot a linked list. I need to remove items and add items to the sorted linked list. Is it possible to create a linked list, sort it using the collection sort and return the sorted linked list? I have looked in the api's but got confused!!

    You don't need to copy anything.
    List list = new LinkedList(); // or ArrayList
    // list.add stuff
    Collections.sort(list); Assuming whatever you added to the list implements Comarable, the list is now sorted.

  • Need help on creating a linked list with array...

    I want to create a linked listed using array method. Any suggestion on how would I start it.
    thanks

    That means I want to implement linked list using an
    array.I believe you mean you want to implement list using an array. Linked list is a very different implementation of a list, which can be combined with arrays for a niche implementation of list, but I don't think this is what you're talking about.
    Do you mind if we ask why you don't want to use ArrayList? It does exactly what you specify, plus it will increase the size of the internal array as necessary to ensure it can store the required elements.
    If you really want to make your own, have a look at the source for ArrayList (in src.jar in your JDK installation folder) - it will answer any questions you have. If you don't understand any of the code, feel free to post the relevant code here and ask for clarification.

  • ObservableList - "Linked list" or "Dynamic array"?

    I always assumed ObservableList (or more precisely, its implementation that is used to store child nodes) to be a linked list. Well, is it? :)
    Thanks for reading!

    stepan wrote:
    Unfortunately, java.util.List is itself only an interface. What I'm concerned with is an actual implementation (i.e. data structure used).
    Let me clarify my motivation by formulating the question more specifically: When dealing with an instance of ObservableList obtained by calling Parent's getChildren() method, will the get(int) method run in O(1) or O(size())? The latter would suggest it really may be a linked list...Previous answers mine included doesn't help much after I re-read your actual question :).
    Barring an actual answer from the Source (One of the Oracle engineers) vs the Source (code.....) I found an answer to your question after digging around in the private packages for a bit. Children nodes to a Parent are initially created as an ArrayList. I suppose its possible that ArrayList could be replaced later by some other implementation of List during a Class's use at runtime (some corner use-case where LinkedList is favored for insertion speed) - but when they are born they are ArrayLists.
    The javafx.scene.Parent class creates children as a VetoableObservableList()..
    private final ObservableList children = new VetoableObservableList() {
    };The constructor for class com.sun.javafx.collections.VetoableObservableList
    public VetoableObservableList()
            super(new ArrayList());
        }

  • After Delete in Linked list...unable to display the linked list

    Hi...i know that there is an implementation of the class Linked Link but i am required to show how the linked list works in this case for my project...please help...
    Yes..I tried to delete some objects in a linked list but after that i am not able to display the objects that were already in the linked list properly and instead it throws an NullPointerException.
    Below shows the relevant coding for deleting and listing the linked list...
    public Node remove(Comparator comparer) throws Exception {
         boolean found = false;
         Node prevnode = head;          //the node before the nextnode
         Node deletedNode = null;     //node deleted...
         //get next node and apply removal criteria
         for(Node nextnode = head.getNextNode(); nextnode != null; nextnode = nextnode.getNextNode()) {
              if(comparer.equals(nextnode)) {
                   found = true;
                   //remove the next node from the list and return it
                   prevnode.setNextNode(nextnode.getNextNode());
                   nextnode.setNextNode(null);
                   deletedNode = nextnode;
                   count = count - 1;
                   break;
         if (found) return deletedNode;
         else throw new Exception ("Not found !!!");
    public Object[] list() {
         //code to gather information into object array
         Node node;
         Object[] nodes = new Object[count];
         node = head.getNextNode();
         for (int i=0; i<count; i++) {
              nodes[i] = node.getInformation();  // this is the line that cause runtime error after deleting...but before deleting, it works without problem.
              node = node.getNextNode();
         return nodes;
    }Please help me in figuring out what went wrong with that line...so far i really can't see any problem with it but it still throws a NullPointerException
    Thanks

    OK -- I've had a cup and my systems are coming back on line...
    The problem looks to be the way that you are handling the pointer to the previous node in your deletion code. Essentially, that is not getting incremented along with the nextNode -- it is always pointing to head. So when you find the node to delete then the line
       prevnode.setNextNode(nextnode.getNextNode());will set the nextNode for head to be null in certain situations (like if you are removing the tail, for instance).
    Then when you try to print out the list, the first call you make is
    node = head.getNextNode();Which has been set to null, so you get an NPE when you try to access the information.
    Nothing like my favorite alkaloid to help things along on a Monday morning...
    - N

  • Problem with Queue and linked list

    Hi... i've got an assignment it start like this.
    You are required to write a complete console program in java includin main() to demonstrate the following:
    Data Structure: Queue, Priority Queue
    Object Involved: Linked-List, PrintJob
    Operations Involved:
    1. insert
    2. remove
    3. reset
    4. search
    Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
    Can any1 tell me wat am supposed to do...

    Hi,
    Why don't you start your demo like this?
    import java.io.IOException;
    public class Demo {
         public Demo() {
         public void startDemo() throws IOException {
              do {
                   System.out.println("String Console Demo ");
                   System.out.println("\t" + "1. Queue Demo");
                   System.out.println("\t" + "2. PriorityQueue Demo");
                   System.out.println("\t" + "3. LinkedList Demo");
                   System.out.println("\t" + "4. PrintJob Demo");
                   System.out.println("Please choose one option");
                   choice = (char) System.in.read();
                   showDemo(choice);
              } while (choice < '1' || choice > '4');
         public void showDemo(char ch) {
              switch (ch) {
              case '1':
                   System.out.println("You have chosen Queue Demo ");
                   showOperations();
                   break;
              case '2':
                   System.out.println("You have chosen Priority Queue Demo ");
                   showOperations();
                   break;
              case '3':
                   System.out.println("You have chosen LinkedList Demo ");
                   showOperations();
                   break;
              case '4':
                   System.out.println("You have chosen Print Job Demo ");
                   showOperations();
                   break;
         private void showOperations() {
              System.out.println("Please choose any operations ");
              System.out.println("\t" + "1. Insert ");
              System.out.println("\t" + "2. Remove ");
              System.out.println("\t" + "3. Reset ");
              System.out.println("\t" + "4. search ");
         public static void main(String[] args) throws IOException {
              Demo demo = new Demo();
              demo.startDemo();
         private char choice;
    Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
    Thanks

  • How to use methods when objects stored in a linked list?

    Hi friend:
    I stored a series of objects of certain class inside a linked list. When I get one of them out of the list, I want to use the instance method associated with this object. However, the complier only allow me to treat this object as general object, ( of Object Class), as a result I can't use instance methods which are associated with this object. Can someone tell me how to use the methods associated with the objects which are stored inside a linked list?
    Here is my code:
    import java.util.*;
    public class QueueW
         LinkedList qList;
         public QueueW(Collection s) //Constructor of QuequW Class
              qList = new LinkedList(s); //Declare an object linked list
         public void addWaiting(WaitingList w)
         boolean result = qList.isEmpty(); //true if list contains no elements
              if (result)
              qList.addFirst(w);
              else
              qList.add(w);
         public int printCid()
         Object d = qList.getFirst(); // the complier doesn't allow me to treat d as a object of waitingList class
              int n = d.getCid(); // so I use "Object d"
         return n; // yet object can't use getCid() method, so I got error in "int n = d.getCid()"
         public void removeWaiting(WaitingList w)
         qList.removeFirst();
    class WaitingList
    int cusmNo;
    String cusmName;
    int cid;
    private static int id_count = 0;
         /* constructor */
         public WaitingList(int c, String cN)
         cusmNo = c;
         cusmName = cN;
         cid = ++id_count;
         public int getCid() //this is the method I want to use
         return cid;

    Use casting. In other words, cat the object taken from the collection to the correct type and call your method.
       HashMap map = /* ... */;
       map.put(someKey, myObject);
       ((MyClass)(map.get(someKey)).myMethod();Chuck

  • Can I import my old link lists into 365 site?

    Hi I would like to import all my hard work from my old 2010 sharepoint site into the new 365 site.
    I exported my links to excel but I cannot see an import option on a link list in 365.
    Surely there must be an easy way to do this that I am missing?
    thanks

    Below are the steps to save List as Template:
    >> Go to the List - List Settings - Click on Save List as Template - Provide Template Name and make sure you check the "With Content" box available on the page. 
    Once the List is successfully saved as template, you will find the template under List Templates gallery. Download that template it should have ".stp" extension. Get that file and upload the file to List Templates gallery of your SharePoint Online Office
    365 site. Then create a new app and there you should find the Template and create a list using that template.
    If you have any questions then let me know.
    Please ensure that you mark a question as Answered once you receive a satisfactory response.

  • Is there a way to create a "Horizontal Links List" from a query?

    Hi,
    Is there a way to create a "Horizontal Links List" from a query?
    I want to display file names that I have uploaded as links to a display page.
    I don't know how to create my own template yet as I've read... I saw Jes had posted this idea...
    Thanks, Bill

    Yes, that is great Chris!
    Thanks for the site....
    Once I dynamically create the HTML for the list how do I feed it into the page?
    as an item? Can I access an HTML region body dynamically?
    Thanks, Bill

Maybe you are looking for