40

In Java, when would it be preferential to use a List rather than an Array?

Dean J
40.5k17 gold badges70 silver badges95 bronze badges
asked Oct 19, 2009 at 16:48

9 Answers 9

46

I see the question as being the opposite-

When should you use an Array over a List?

Only you have a specific reason to do so (e.g.: Project Constraints, Memory Concerns (not really a good reason), etc.)

Lists are much easier to use (imo) and have much more functionality.

Note: You should also consider whether or not something like a Set, or another data structure is a better fit than a List for what you are trying to do.

Each data structure, and implementation, has different pros/cons. Pick the ones that excel at the things that you need to do.

If you need get() to be O(1) for any item? Likely use an ArrayList, Need O(1) insert()? Possibly a Linked List. Need O(1) contains()? Possibly a Hashset.

TLDR: Each data structure is good at some things, and bad at others. Look at your objectives and choose the data structure that best fits the given problem.

Edit:

One thing not noted is that you're better off declaring the variable as its interface (i.e. List or Queue) rather than its implementing class. This way, you can change the implementation at some later date without changing anything else in the code.

As an example:

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

vs

List<String> myList = new LinkedList<String>();

Note that myList is a List in both examples. --R. Bemrose

Bö macht Blau
13k5 gold badges44 silver badges64 bronze badges
answered Oct 19, 2009 at 17:15
6
  • Linked List is not O(1) insert unless you are inserting elements at the beginning or the end. Its main purpose is custom implementations of stacks and queues. Commented Oct 19, 2009 at 18:12
  • 1
    Linked list insert is O(1) at a known location. You can do an O(1) insert in the middle of the list. Finding the place to insert may be O(n) if your list is not a queue or a stack. The distinction is important when trying to compare data structures. Commented Oct 19, 2009 at 18:20
  • 2
    One thing not noted is that you're better off declaring the variable as its interface (i.e. List or Queue) rather than its implementing class. This way, you can change the implementation at some later date without changing anything else in the code. Commented Oct 19, 2009 at 18:32
  • 2
    As an example: List<String> myList = new ArrayList<String>(); or List<String> myList = new LinkedList<String>(); Note that myList is a List<String> in both examples. Commented Oct 19, 2009 at 18:35
  • 1
    This answer actually doesn't say anything about benefits of T[] over ArrayList<T> and/or benefits of ArrayList<T> over T[]. While choice between all other container types (e.g. ArrayList<T> vs LinkedList<T>, or ArrayList<T> vs HashSet<T>, etc) is quite obvious, the choice between ArrayList<T> and T[] isn't (because both arrange items in memory sequentially), so this answer actually doesn't address the main question. Commented Apr 19, 2016 at 9:40
19

Rules of thumb:

  • Use a List for reference types.
  • Use arrays for primitives.
  • If you have to deal with an API that is using arrays, it might be useful to use arrays. OTOH, it may be useful to enforce defensive copying with the type system by using Lists.
  • If you are doing a lot of List type operations on the sequence and it is not in a performance/memory critical section, then use List.
  • Low-level optimisations may use arrays. Expect nastiness with low-level optimisations.
answered Oct 19, 2009 at 17:19
0
12

Most people have answered it already.

There are almost no good reason to use an array instead of List. The main exception being the primitive array (like int[]). You cannot create a primitive list (must have List<Integer>).

The most important difference is that when using List you can decide what implementation will be used. The most obvious is to chose LinkedList or ArrayList.

I would like to point out in this answer that choosing the implementation gives you very fine grained control over the data that is simply not available to array:

  1. You can prevent client from modifying your list by wrapping your list in a Collection.unmodifiableList
  2. You can synchronize a list for multithreading using Collection.synchronizedList
  3. You can create a fixed length queue with implementation of LinkedBlockingQueue
  4. ... etc

In any case, even if you don't want (now) any extra feature of the list. Just use an ArrayList and size it with the size of the array you would have created. It will use an Array in the back-end and the performance difference with a real array will be negligible. (except for primitive arrays)

answered Oct 19, 2009 at 18:08
8

Pretty much always prefer a list. Lists have much more functionality, particularly iterator support. You can convert a list to an array at any time with the toArray() method.

answered Oct 19, 2009 at 16:53
4
  • "particularly iterator support": note that the enhanced for loop supports arrays as well as Lists. Commented Oct 19, 2009 at 17:04
  • Though not as functional as a true iterator, the new for-loop in Java 5 gives syntactic sugar for iterating over arrays. Commented Oct 19, 2009 at 17:08
  • Right, like Michael said, the for loop is syntactic sugar. There are times where you need your object to implement Iterator, such as passing Lists to things like a Comparator. Commented Oct 19, 2009 at 17:24
  • @Chris Kessel: Yeah, except the Arrays class has a static method that takes an array and a Comparator that you should be using with an array: java.sun.com/javase/6/docs/api/java/util/… Commented Oct 19, 2009 at 17:32
5

Always prefer lists.

Arrays when

  1. Varargs for a method ( I guess you are forced to use Arrays here ).
  2. When you want your collections to be covariant ( arrays of reference types are covariant ).
  3. Performance critical code.
answered Oct 19, 2009 at 17:26
3

If you know how many things you'll be holding, you'll want an array. My screen is 1024x768, and a buffer of pixels for that isn't going to change in size ever during runtime.

If you know you'll need to access specific indexes (go get item #763!), use an array or array-backed list.

If you need to add or remove items from the group regularly, use a linked list.

In general, dealing with hardware, arrays, dealing with users, lists.

answered Oct 19, 2009 at 17:19
2
  • Not sure about the screen example - you can resize the screen size anytime. That is even common if you are for example using RemoteDesktop/citrix or move an application to the 2nd screen. Commented Oct 19, 2009 at 18:13
  • 1
    If you move an application screen-to-screen, you're dealing with a window, not a screen, which is something dealing with a user, not hardware. If you're opening a remote desktop, it's a new initialization/runtime. I don't want to nitpick too much, but I'd like to stand by what I said. :) Commented Oct 20, 2009 at 13:58
1

It depends on what kind of List.

It's better to use a LinkedList if you know you'll be inserting many elements in positions other than the end. LinkedList is not suitable for random access (getting the i'th element).

It's better to use an ArrayList if you don't know, in advance, how many elements there are going to be. The ArrayList correctly amortizes the cost of growing the backing array as you add more elements to it, and is suitable for random access once the elements are in place. An ArrayList can be efficiently sorted.

answered Oct 19, 2009 at 16:53
0

If you want the array of items to expand (i.e. if you don't know what the size of the list will be beforehand), a List will be beneficial. However, if you want performance, you would generally use an array.

answered Oct 19, 2009 at 16:53
1
  • 2
    To be precise: If you like to micro-optimize, you would generally use an array. Commented Oct 19, 2009 at 16:54
0

In many cases the type of collection used is an implementation detail which shouldn't be exposed to the outside world. The more generic your returntype is the more flexibility you have changing the implementation afterwards.

Arrays (primitive type, ie. new int[10]) are not generic, you won't be able to change you implementation without an internal conversion or altering the client code. You might want to consider Iterable as a returntype.

answered Oct 19, 2009 at 17:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.