aspose file tools*
The moose likes Java in General and the fly likes When to use array instead of ArrayList? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When to use array instead of ArrayList?" Watch "When to use array instead of ArrayList?" New topic
Author

When to use array instead of ArrayList?

Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 670
ArrayList is growable as compared to Array and thus has advantage over array but about the other way round? Are there cases when normal array should be used instead of ArrayList?

Thanks
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2615
    
    9

As you already pointed out the major difference between the 2 is the size. Array is fixed, ArrayList is growable. Furthermore, the API allows you to switch from array to list and vice versa.

If the number of elements is fixed, use an array. I don't know if memory can be a factor eg maybe array uses less memory on the stack and heap.


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5 OCPBCD5
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 232

I prefer to use Arrays over ArrayLists whenever I know I am only going to work with a fixed number of elements. My reasons are mostly subjective, but I'm listing them here anyway:

Using Collection classes for primitives is appreciably slower since they have to use autoboxing and wrappers.

I prefer the more straightforward [] syntax for accessing elements over ArrayList's get(). This really becomes more important when I need multidimensional arrays.

ArrayLists usually allocate about twice the memory you need now in advance so that you can append items very fast. So there is wastage if you are never going to add any more items.

(Possibly related to the previous point) I think ArrayList accesses are slower than plain arrays in general. The ArrayList implementation uses an underlying array, but all accesses have to got through the get(), set(), remove(), etc. methods which means it goes through more code than a simple array access. But I have not actually tested the difference so I may be wrong.

Having said that, I think the choice actually depends on what you need it for. If you need a fixed number of elements or if you are going to use multiple dimensions, I would suggest a plain array. But if you need a simple random access list and are going to be making a lot of inserts and removals to it, it just make a lot more sense to just use an Arraylist


SCJP 6- 91%, IBM DB2, IBM RAD Certified
Volodymyr Levytskyi
Ranch Hand

Joined: Mar 29, 2012
Posts: 505
    
    1

I recommend to use ArrayList almost whenever you want to use array.

Because it is just a wrapper around array that has all methods very efficient .

I remember I was using plain array and found myself writing my own ArrayList because of growing needs of my simple application.

ArrayList is really fast and protects you from turning around with concerns you meet when using plain array.

Also think of object oriented programing.
ArrayList should take care of your array but not your code which deals with its concerns.

By using plain array you will write in future your own ArrayList to separate concerns of your code and code that handles functionality of your array.


True person is moral, false is right!
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61760
    
  67

I will almost always use a List implementation (not always ArrayList) in place of arrays. Worrying about the extra memory it may consume is a micro-optimization that is almost always needless.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1049
    
  15
Also one of the great benefits of collection implementations is they give you a lot of flexibility. So depending on your need, you can have a List behave as an ArrayList or as a LinkedList and so on. Also if you look at the Collection API, you'd see you have methods for almost everything you'd ever need to do.

I'd always give preference to flexibility cause being able to adapt to change is an implied requirement almost always.

The concurrent API gives you multi-threading support and hence even more flexibility.

Another thing to consider might be Arrays.asList() and List.toArray() methods. As far as I remember Arrays.asList() makes the changes in both the array and the List whereas the Array you get after List.toArray() is an array that is unaffected by the changes to the source List. However I'm not sure about this last point. You might want to test it.

Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 670
Thanks All.

I now know that arrayList consumes more memory than ArrayList.Iwill read more on that.

Bear Bibeault wrote
I will almost always use a List implementation (not always ArrayList) in place of arrays. Worrying about the extra memory it may consume is a micro-optimization that is almost always needless.


If developers almost always use ArrayList then why does Array also exist in Java.? If everything that array provides is provided by ArrayList with more advantages then why would array ever be used?

thanks again.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61760
    
  67

Because almost always isn't always.
Volodymyr Levytskyi
Ranch Hand

Joined: Mar 29, 2012
Posts: 505
    
    1

Plain array exist in Java because ArrayList,ArrayDeque,HashMap,Stack,Vector uses plain java array.
Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 670
Because almost always isn't always


What would be exception cases where arrays would be preferred over arrayList?

thanks
Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 670
Plain array exist in Java because ArrayList,ArrayDeque,HashMap,Stack,Vector uses plain java array.


So arrayLists itself uses arrays internally.

thanks.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61760
    
  67

Off the top of my head, I'd use an array if I was setting up a static list of things. Also, many APIs expect or return arrays. Or, if I have any reason to think an array would make things clearer than a List.
Volodymyr Levytskyi
Ranch Hand

Joined: Mar 29, 2012
Posts: 505
    
    1

To be Junior Java Developer you must know Java Core!

Please cover at least my tutorials on Java collections.

Thanks!
Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 670
thanks all
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8413
    
  23

Monica. Shiralkar wrote:Are there cases when normal array should be used instead of ArrayList?

You've had plenty of opinions, so here's mine:
  • When the number of elements MUST be fixed.
  • When memory is at a premium. An int[] is generally a LOT smaller than an ArrayList<Integer>.
  • When time is at a premium. values[x] is quicker than values.get(x) (but probably not as much quicker as you think).
  • When the cost of conversion (eg, int to/from Integer) is significant.

  • Other than that, like Volodymyr, I can't think of an earthly reason why you would use an array.

    Winston

    Isn't it funny how there's always time and money enough to do it WRONG?
    Articles by Winston can be found here
    Winston Gutkowski
    Bartender

    Joined: Mar 17, 2011
    Posts: 8413
        
      23

    Monica. Shiralkar wrote:Are there cases when normal array should be used instead of ArrayList?

    I missed one, and it's quite important:
  • When elements are sparse; ie, when removing an element doesn't affect the position of the others. This usually means that the array can't hold nulls.

  • This is a major difference between arrays and Lists. The only normal way to "remove" an element from an array is to set it to null or, in the case of a primitive array, to some value that can't possibly be "real". The indexes of other elements are not affected.

    Winston
    Monica. Shiralkar
    Ranch Hand

    Joined: Jul 07, 2012
    Posts: 670
    Thanks. I have a doubt. In array we can assign a a particular position by below syntax:



    Why we do not have such kind of syntax for assigning at particular position in arrayList? I know its possible by why no stratightforward syntax for doing this in arrayList.

    thanks.
    Paul Clapham
    Bartender

    Joined: Oct 14, 2005
    Posts: 18987
        
        8

    I'm sure there is a method for assigning an object to a particular entry of a List. It's true it isn't "syntax", but I don't think that calling a method is such a serious problem.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61760
        
      67

    Why should ArrayList, out of the many Java collections, get special syntax in the language? Makes no sense.
    Winston Gutkowski
    Bartender

    Joined: Mar 17, 2011
    Posts: 8413
        
      23

    Monica. Shiralkar wrote:Why we do not have such kind of syntax for assigning at particular position in arrayList?

    You do: ArrayList.set(int, E), which even returns you the previous value at that position. The difference is that it only works within the current bounds of the List, and Lists are dynamic.

    What you want (I think) is more akin to Map.put(K, V).

    I suggest you read the API docs for all the major collection types, especially java.util.List, because it will probably answer most of your questions.

    Winston

    PS: There is one collection that works the way you want: BitSet; but it's highly specialized.
    Monica. Shiralkar
    Ranch Hand

    Joined: Jul 07, 2012
    Posts: 670
    Thanks all
    Piet Souris
    Ranch Hand

    Joined: Mar 08, 2009
    Posts: 700
        
      11
    Sorry to step in so late, but I just read this topic.

    A very simple example where you would use arrays over ArrayLists and the like is in board games.

    In my chess and checkers program I simply use: int[][] board = new int[8][8].

    I wouldn't dream of using:

    and then getting the piece on square a1 as:
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: When to use array instead of ArrayList?