Prefer lists to arrays

Posted on 2011-04-26
Last Modified: 2012-05-11

Prefer lists to arrays

I was reading above staemtent. I have not understood the statement, concept behind clearly.
Please advise. Any ideas, sugestions, sample code, links, resources highly appreciated. thanks in advance
Question by:gudii9
    LVL 47

    Expert Comment

    LVL 23

    Assisted Solution

    Where is the source of this statement.

    Actually it depends whether we want to use Array or List.
    When we know the size, it is better to use Array rather than list.
    LVL 47

    Expert Comment

    arrays I guess should be faster, but lists are much easier
    in programmimg even when you can know the limit on size

    In manyy practical cases when you deal with collections within a few hundred -
    the perfoermance difference you probably would not notice, but convenience and ease
    of thinking is worth a lot.

    Collections have a lot of conveniecnce methods - like insertuing at any element,
    checking contains(), and a lot of others which are convenient to use.
    Unless you have really computation heavy operations with a lot of collections operations
    or very big collections - I'd vote for lists

    LVL 92

    Expert Comment

    Main reason os that arrays are covariant while Lists (with generics) are invariant.

    Covariant: This will fail at runtime

    Object[] array = new String[4];
    array[0] = 5;

    Invariant: This will not compile

    List<String> list = new ArrayList<String>();

    Better to pick up errors at compile time
    LVL 7

    Author Comment

    >>Unless you have really computation heavy operations with a lot of collections operations
    or very big collections - I'd vote for lists

    if eavy operations with a lot of collections operations or very big collections then better to use array. Why?

    Main reason os that arrays are covariant while Lists (with generics) are invariant.

    what are differences between covariant and invariant. please advise
    LVL 47

    Expert Comment


    Well, array probably takes less resources per element that ArrayList.
    Therefore when you really have huge cllections and you are concerned with memory then
    array would probably save you some more memrory space.
    Beside, because ArrayList provide you a lot of concvenience -
    in a sense of more flexible in adding new elements moveing tem around, so it will
    have some time overhead with it. And again this beciomes important when you
    are doing millions of operations iwith millions of elements.
    When you do som eregular perogrammisng with r
    sizes not comparable withmemory then convenience in prigramming
    usually trumps these differences which user will not notice.
    With huge numbers situation may be changing - and you can
    accomplish something with arrays, whereas with collections
    you'll not have enough mmemory.
    LVL 47

    Expert Comment


    This is a plausible explanation about covariance of ararys and lack of covariance
    for collections:

    While you might find it helpful to think of collections as being an abstraction of arrays, they have some special properties that collections do not. Arrays in the Java language are covariant -- which means that if Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a Number[], and you are free to pass or assign an Integer[] where a Number[] is called for. (More formally, if Number is a supertype of Integer, then Number[] is a supertype of Integer[].) You might think the same is true of generic types as well -- that List<Number> is a supertype of List<Integer>, and that you can pass a List<Integer> where a List<Number> is expected. Unfortunately, it doesn't work that way.

    It turns out there's a good reason it doesn't work that way: It would break the type safety generics were supposed to provide. Imagine you could assign a List<Integer> to a List<Number>. Then the following code would allow you to put something that wasn't an Integer into a List<Integer>:

    List<Integer> li = new ArrayList<Integer>();
    List<Number> ln = li; // illegal
    ln.add(new Float(3.1415));

    Because ln is a List<Number>, adding a Float to it seems perfectly legal. But if ln were aliased with li, then it would break the type-safety promise implicit in the definition of li -- that it is a list of integers, which is why generic types cannot be covariant.
    LVL 92

    Assisted Solution

    following gives a good discussion of the point I made earlier about covarient and invarient

    generics allow you to pick up error at compile time,whereas arrays won't fail until runtime
    this is the main reason to pick lists over arrays, most of the other mentioned in this thread are actiually application dependant so not really relevant for a general discussion.
    LVL 7

    Author Comment

    generics allow you to pick up error at compile time,whereas arrays won't fail until runtime
    this is the main reason to pick lists over arrays,

    can you please elaborate on this
    LVL 47

    Accepted Solution


    If you have array of Objects, like
    Object [] array = new Object[20];
    You can place any object in this array.
    If in fact you expect only instances of certain class
    in this array - you'll discover it only during exeecution
    when you say
    String s = (String)array[5];
    compiler will accept this, but if your element array[5] cannot be cast to String you'll
    get Runtime Error during execurtion.

    If you work with say arraylist  you have
    the ability using generics, to specify

    ArrayList<String> ar = new ArrayList<String>();
    then when you add
    compiler wil check and it will raise error at compile time
    in case  s is not a String.

    It always saves time when you discover problems at compile time rather than
    at the excution time and that is the advantage of Generics.

    While I understand and appreciate this point made by objects as beineg an advantge of Lists over arrays,
    I would have some reservations saying that this the MAIN
    reason to pick lists over arrays.

    I almost always preferred Vector over arrays long before any Generics
    were even introduced to Java.
    Main reasons being that one thing - you don't need
    to decalare upfront the size, as you need with arrays (in most cases
    you simply don't know the size upfront - say when you readuing your data from database).
    Another reason is that collections are much more flexible - you can
    easily remove elements from the middle of the vector or arraylist.

    You have to pay with some performance and memeory for these
    programming conveniences, but unless you enter the area where you have really huge
    numbers of elements these payments you make are
    far less important than progarmming convenience you get with the
    lists and vectors.

    Frankly, i almost never use arrays, as lists or vectors are indeed much more convenient.
    And most of my tasks do not go to such huge numbers, that the
    performace and memory differences become important.


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    EvenOdd challenge 10 69
    Connect to IP Camera using Java 4 62
    Unable to open debugger port in Intellij idea 6 39
    wordlen challenge 3 30
    Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
    Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
    Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
    This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now