Design choice between ArrayList and LinkedList

Can someone clarify me which is better suited (efficient) for use?
It appears to me that both can be used very much interchangeably at least from functionality point of view. :(

Using the following code (and I'm sure someone will come nitpicking about it) I get the (expected, at least by me from prior experience) result that iteration over a LinkedList is about twice as fast as iteration over an ArrayList, but lookup operations on an ArrayList are substantially faster:
package jtw.test;
import java.util.*;
public class SpeedTest {
    public static void main(String... args) throws Exception {
        List<Integer> linked = new LinkedList<Integer>();
        List<Integer> arr = new ArrayList<Integer>();
        for (int i = 0; i < 1e3; i++) {
            linked.add(i);
            arr.add(i);
        long r = 0;
        Date startLinked = new Date();
        for (int i = 0; i < 1e3; i++) {
            for (Integer q: linked) {
                 r += q;
        Date stopLinked = new Date();
        System.out.println("Total: " + r);
        r = 0;
        Date startArr = new Date();
        for (int i = 0; i < 1e3; i++) {
            for (Integer q: arr) {
                 r += q;
        Date stopArr = new Date();
        System.out.println("Total: " + r);
        System.out.println("LinkedList iteration: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
        System.out.println(" ArrayList iteration: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
         r = 0;
        startLinked = new Date();
        for (int i = 0; i < 1e3; i++) {
            for (int j = 999; j >= 0; j--) {
                 r += linked.get(j);
        stopLinked = new Date();
        System.out.println("Total: " + r);
        r = 0;
        startArr = new Date();
        for (int i = 0; i < 1e3; i++) {
            for (int j = 999; j >= 0; j--) {
                 r += arr.get(j);
        stopArr = new Date();
        System.out.println("Total: " + r);
        System.out.println("LinkedList lookup: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
        System.out.println(" ArrayList lookup: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
}Gets the result:
D:\jdk1.6.0_05\bin\java -Didea.launcher.port=7540 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\bin" -Dfile.encoding=windows-1252 -classpath "D:\jdk1.6.0_05\jre\lib\charsets.jar;D:\jdk1.6.0_05\jre\lib\deploy.jar;D:\jdk1.6.0_05\jre\lib\javaws.jar;D:\jdk1.6.0_05\jre\lib\jce.jar;D:\jdk1.6.0_05\jre\lib\jsse.jar;D:\jdk1.6.0_05\jre\lib\management-agent.jar;D:\jdk1.6.0_05\jre\lib\plugin.jar;D:\jdk1.6.0_05\jre\lib\resources.jar;D:\jdk1.6.0_05\jre\lib\rt.jar;D:\jdk1.6.0_05\jre\lib\ext\dnsns.jar;D:\jdk1.6.0_05\jre\lib\ext\localedata.jar;D:\jdk1.6.0_05\jre\lib\ext\sunjce_provider.jar;D:\jdk1.6.0_05\jre\lib\ext\sunmscapi.jar;D:\jdk1.6.0_05\jre\lib\ext\sunpkcs11.jar;F:\dev\Euler\out\production\Euler;C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain jtw.test.SpeedTest
Total: 499500000
Total: 499500000
LinkedList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 30
ArrayList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 53
Total: 499500000
Total: 499500000
LinkedList lookup: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 424
ArrayList lookup: Wed Jan 21 07:32:42 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 22
Process finished with exit code 0Given the internal representation of the datatypes, this is to be expected.

Similar Messages

  • Differece between ArrayList and LinkedList

    Differece between ArrayList and LinkedList

    An array list is implemented as an array. A LinkedList is implemented as a series of separate nodes linked by references.
    Although they both support the same methods, that has performance implications. Linked lists are better at inserting and deleting arbitary elements, but are slow to reference an element by index.

  • Both of the advantages of ArrayList and LinkedList are needed.

    Hi there,
    I wonder how if I want performance on random access an ArrayList and also remove elements in any position of the List? As far as I know that a LinkedList is the best choice if I want to remove elements in any position of the List, but it's slow on traversing the List. Sometimes it's hard to choose between ArrayList and LinkedList, is there a way that I could have both advantages of ArrayList and LinkedList?
    Any suggestion?
    Thanks,
    Jax

    I think you might be interested in the data structure
    called a deque. It is built for fast insertions
    at both ends and is usually implemented as a linked
    list of arrays. The standard collections API does not
    offer this data structure (I wish it did). So you have
    to find a 3rd party implementation. Try searching
    Google: http://www.google.com/search?q=java+deque
    Thanks nasch and pervel for the information. What do you think if I do something like this?
    List a = new ArrayList();
    // perform some tasks that is fast with ArrayList
    List b = new LinkedList(a);
    // perform some tasks..
    Although a new object is created, but that perform better than one ArrayList or one LinkedList solely.

  • Making choice between socket and RMI

    I never use RMI, but i am familiar to socket programming. i want to write an online game, I know that use RMI will easy than use socket, could anyone tell me what factors will affect the choice between using socket and RMI if don't consider which one i am familiar ?
    thanks
    jacky

    I would consider the amount of traffic your online game is going to be generating. Obviously, if the traffic is the bottleneck, you will want to optimize it as much as possible.
    I can see that if you are familiar with sockets and socket programming, where this is very appealing because after all, you can't get much faster than raw sockets. Also, the Java APIs around sockets are much easier than the equivalent BSD Socket C/C++ libraries.
    Still, RMI has much more to offer.
    o It is relatively easy to set up a connection
    o exceptions will be thrown when problems occur
    o serializing classes is so easy it's laughable
    o If performance becomes an issue, you can (as the previous poster suggests) create your own custom socket factory which optimizes the used bandwidth. Options here include compression if you have the CPU cycles to spare.
    o There are mechanisms in place for working RMI over firewalls
    Many of the things that RMI offers, you might find yourself re-writing in your own socket-based API. Personally, I would choose RMI.

  • When to choose ArrayList and LinkedList ?

    Please let me know which list type to use and when ? Pros Cons .. Advantages Disadvantages
    ArrayList vs LinkedList ?

    Here is a good place to start [http://www.google.co.uk/search?q=arraylist+vs+linkedlist] 154,000 hits. I think most of the arguments are covered here. ;]

  • OS should allow choice between "deep" and "light" sleep (battery life)

    It's clear that Apple needs to fix the OS for the ipod touch so that the user can choose between one of two sleep modes. A "deep" sleep mode would be similar to sleep in pre- OS 4.1: WIFI would be automatically turned off to preserve battery. A "light" sleep mode would be similar to the sleep mode in the current OS 4.1 and would not shut WIFI off (but thereby quickly draining the battery).

    you might want to let Apple know via _*iPod Touch Feedback*_.
    JGG

  • Choice between T540p and T440p

    Hello all,
    I am new in this forum, so I am very excited to start.
    I am planning to buy either the T440p or T540p and I need to consult with you guys in order to make a good choice
    My needs are for a lightweight business laptop which features very good display/keyboard, has a very good battery performence and has a good three years international guarenty. Also, the price matters to me very much.
    Unfortunately, the the T440p is not offered with such warenty - only 1 year, and no IPS displat. However, other specs are what I need. The T540p has the 3 year warenty but is much havier and its batery will not last as the T440p.
    When I looked at the Lenovo site the picture becomes more complecated. The T440p is much more expensive compared to the T540p - more than $1,000 compared to $649, with more or less the same specs.
    So what should I do? I would pay the extra money for the T440p if it had the same warenty, but it is not available in Lenovo website. Just imagining carrying a 5.5lbs piece of mettal compared to the 4.7lbs' T440p (which is not a feather by itself) gives me an instant backpain...
    Thanks again,
    Uzi

    I'm not sure if either the T440p or the T540p is really considered lightweight. Maybe the T440s? Or X240s?
    W520: i7-2720QM, Q2000M at 1080/688/1376, 21GB RAM, 500GB + 750GB HDD, FHD screen
    X61T: L7500, 3GB RAM, 500GB HDD, XGA screen, Ultrabase
    Y3P: 5Y70, 8GB RAM, 256GB SSD, QHD+ screen

  • Choice Between IDOC and ABAP Proxy

    Hello All,
    We are building a Bi Directional Interface for Business partners between a third Party ERP, XI and SAP CRM.
    We are looking for some advise on the best way to go forward between the two options below:
    a) Do an ABAP Proxy Call on Fn Module CRMXIF_PARTNER_SAVE  from XI
    b) Create and IDOC in CRM
       ( Message Type CRMXIF_PARTNER_SAVE_M )
    Not being an XI consultant, my understanding is as follows
    Option A  : Gives me the flexibility to format my response in the manner we like. But this is a synchronous call. Also this is a generated RFC. So changes in the XIF layer of CRM could be an issue.
    Option B : Response can be achieved only through the ALE Audit Functionality, which has a predefined message structure. For Eg: If I wanted to send the response in the same format as the incoming message with an added segment for the error, this is not possible. Ofcourse, I get all the functionalities of monitoring and Handling IDOCs in this option.
    Any thoughts on the advantages and disadvantages of each option would be greatly appreciated.
    Thanks
    Anoop

    Anoop,
    I probably should have mentioned in the BLOG, that IDOC is good if its a standard IDOC, so that you don't have under go the pain doing the modifications for the custom one.
    In your case, PROXY might make more sense as you are saying that you have to do some custom processing as well. So, you can call the BAPI / Function for the standard processing and then do the custom processing in your Proxy code. And more over, if you have want to have a Synch interface, then you cannot use IDOC.
    So, the options in this case boil down to PROXY / RFC.
    PROXY will definitely have the advantage as its going to bypass the adapter engine and directly interact with the Integration server. And moreover, even if you already have a RFC, you can always call that inside your PROXY. However, the only flip side here compared to IDOC, is that you will have to create all your IR objects manually.
    Hope this helps you in making your decision.
    regards,
    Ravi
    Note : Please mark the helpful answers.

  • Choice between 8520 and 9300

    Hi, I'm in a bit of a dilemma, I would like to buy a BB but dont know which model to take, either the 9300 or the 8520. I have read through the differences between the 2 handsets and more or less the 9300 is better on paper.
    The provider is offering me the BB 9300 for 190 pounds (I'm just converting this into pounds) MORE than the 8520.
    My question is that,  is the 9300 a 190 pounds more better than the 8520?
    Thank you

    Hi and welcome
    Good thinking to check first. Thanks for converting into £ but this is multi-national so no need. Now as you have done I will explain about here in the UK.
    I'm guessing you are in the US and it seems to me you guys pay a fortune for devices and still have to buy carrier time.
    In the UK, at present, if you sign up for an 18 month carrier contract which will cost around £10 per month inc 500Mb data you get the 8520 FREE, nada, zip. And you get 12 months carrier warranty on the device as well. Maybe there are similar deals around you?
    The 8520 does not have GPS functionality and this makes it cumbersome for applications that rely on location settings such as FB Places and many others.
    The 8520 is unlikely to receive the latest software  - OS 6 due to limitations of the memory/processor. OS 6 is available for the 9300 and will probably come pre-loaded. There's nothing wrong with OS 5 but it cannot be upgraded on the 8520.
    Whichever you choose, make sure you have a data plan; without data you seriously limit the functionality of any BB and don't worry about extra data costs unless you have no Wi-Fi at home and want to be downloading music/video constantly. Last month, I used 2.6Mb of my 500Mb allowance.
    Good luck and hope to see you on here regularly.
    Blackberry Best Advice - Back-up weekly
    If I have helped you please check the "Kudos" star on the right >>>>

  • Choice between BI and CRM/SRM-Technofunctional.

    Hi all,
    Please tell me marketwise and onsitewise which one is better between Netweaver-BI
    and
    CRM/SRM functional-ABAP  (i.e. technofunctional with higher modules)as i am an ABAPer .
    Thanks.

    llll

  • Choice between VISA and GPIB drivers

    I have a waveform generator with a GPIB port. I would like to build my own VIs. Can someone suggest which driver (VISA or GPIB or IVI) would be preferable and what are the differences in terms of ease among these drivers?

    Hello Craig,
    I have an Agilent 33220A frequency generator for which I have already found drivers from the Instrument Driver Network. I am a beginner in LABVIEW and am in the process of improving my skills in communicating with instruments. So far, I have been communicating with other instruments using VISA and a serial port.
    While going through LABVIEW HELP, I realized that VISA, GPIB and IVI drivers can be used for communicating with a GPIB instrument port. This being the case, I would like to know which of the above-mentioned drivers is preferable?
    Thanks
    Ram

  • Choice between xquery and parsing methods

    I want to read from an xml source file. I have been working with parse techniques (JAXP )and Marshal/Unmarshal techniques(JAXB).
    Recently i came to know that we can query an xml document using xquery and
    xpath methods.
    Is the second method advantageous than the first one in terms of time and memory constraints ?

    Yes, xquery and xpath are always easy to work than parsing on your own.
    It provides already written methods for u, which u need not to write on your own to fetch the data.
    Hope this will help u.
    ......yogesh

  • Choice between syncronous and asyncrous BDC

    HI Experts,
    can you kindly guide when one shall go for asynchronous BDC and when for syncronous BDC?
    Thanks.

    Hi Sanjay,
    There are several answers to this question already in the forum - just do a search!

  • Choice between JSP and Servlet

    I am new to JSP and Servlet. I know JSP container will convert JSP to servlet
    eventually. But in application development's standpoint, anything can be
    done in servlet can also be done in JSP? Some people told me we can
    use the combination of both in one application.
    My question is in what situation we use JSP alone, servlet alone, or
    combination of both??
    Please advise. Thanks!!

    Use a combination of both.
    Your Web application should have a single servlet that all HTTP requests are POSTed to. All the servlet does is act like a traffic cop: it figures out what the request is, delegates to other objects that do the work, and forward the result to the next JSP, whatever that is. It's called a front controller servlet.
    The JSPs should just be pure dynamic presentation. Everything displayed in the pages should have been generated by the servlet and its helper classes. No database queries, etc. Your JSPs will be a lot better off if you learn JSTL and eliminate all scriptlet code.
    Check out frameworks like Struts.

  • Which is better? ArrayList or LinkedList

    Do you know which one is better between ArrayList and LinkdedList in terms of performance, speed and capacity?
    Which one do you suggest to use ?
    Thanks

    It depends upon how the list is going to be used. ArrayLists and LinkedLists work differently -- you need to think about how they each store their data.
    ArrayLists store their list items in, well, arrays. This makes them very fast at addressing those items by index #. So any implementation that needs a lot of random access to the list, such as sorting, is going to be relatively fast.
    The downside of storing the list in an array presents itself when it comes time to add more items to the list. When it runs out of space in the array, it must create a new larger array and copy the items over to it. Also, if you need to insert or remove an item anywhere other than the end of the list, ArrayList must shift the subsequent items in the list by doing an array copy.
    This can be a real drag if you're implementing a queue. This is where LinkedList shines. Each item in the list points to the next and previous ones in the list. Inserting, appending or removing list items involves a couple simple assignment statements. No reallocations or large memory copies are involved. Access is easy as long as it is sequential.
    Random access in a linked list is problematic however. In order to get to the Nth item in the list, LinkedList must start with the first item in the list and step through the list N-1 times. An order of magnitude slower than using an ArrayList.

Maybe you are looking for

  • Print to pdf and then email...

    I frequently print a document to pdf and then email it as an attachment.  The print dialog box allows me to save as pdf or email as pdf.  I would like a print plugin that does both actions - allows me to name and save the pdf to a specified location

  • Acrobat 9 freezes when I open a PDF form

    I've looked through the forums, found similar issues, but not one that seems to offer an answer. When I opened a form (set up for online fill in) and try to edit the text to change an address on the form, Acrobat freezes. I can't even get it to quit

  • Computer halts...what can I do?

    Hello guys, I need your precious help. 4-5 times the day my system goes very slowly for some minutes, it almost halts and cant even move the mouse. There is no proof that it happens when I do "heavy jobs" because it has happened even when was editing

  • How to use ConnectionPoolDataSource object?

    i use embedded OC4J server, build in data-source.xml file the information about DataSource object and try to organized ConnectionPoolDataSource object, but a java.lang.ClassCastException rises. The problem is, i need to use a pooled connection dataso

  • Broadcom-wl [SOLVED]

    Ok so I'm a little tired and just started troubleshooting this, but just in case I don't get it solved tonight: Been away for a few weeks and finally did updates, specifically everything up to kernel .32 including a new broadcom wl driver, version 5.