0

Very much a beginner question here, but hopefully a pertinent one.

I've been attempting to teach myself Java by way of coding a crappy little roguelike. Since I discovered the collections framework, I've found that I'm using arraylists absolutely everywhere - so much so in fact that I find myself worrying I’m being woefully inefficient by using them in places where a regular array would suffice.

Thus my question is this: Under what circumstances should I favour using an arrayList over a regular array (or vice-versa) and why? Is there some kind of simple rule of thumb to help me pick which I should be using for any given task?

I refute that this duplicates Array or List in Java. Which is faster? - my question asks in which situation one is more methodologically sound than the other, and not which is generally quicker for any given task.

Community
  • 1
  • 1
Ben Edwards
  • 168
  • 13
  • 3
    This has been asked before: http://stackoverflow.com/questions/716597/array-or-list-in-java-which-is-faster – jiaweizhang Nov 20 '15 at 15:41
  • 1
    When you know the size of you list before hand and you do not require to increase the size use array otherwise use arraylist. – Sanjeev Kumar Nov 20 '15 at 15:42
  • 1
    If the size of your `collection` will change use `ArrayList` if not use `Array`. – brso05 Nov 20 '15 at 15:42

2 Answers2

4

As said in Effective Java, one should prefer Lists to arrays. One of the major differences is that arrays are covariant by their type and thus need accurate handling. Also, their type is reified and they do not mix well with generics.

But the implication is that arrays are able to work with primitives while generic collections aren't: they have Objects inside. So you might prefer arrays in performance critical parts of your code to avoid primitives boxing-unboxing.

hotkey
  • 140,743
  • 39
  • 371
  • 326
2

If you know that your collection will always be a fixed length then use array.

If your collection is variable in length, I.e it could hold 1,5,100 values then use arraylist.

Example.

An application that asks the user a series of questions, the user can try get the answer right as many times as they like.

You create an array of possible answers to a question, you know there will only ever be 5 possible answers for each question, you would use an array of length 5 to store the possible answers.

You decide to create an array of all the answers the user submits, they could submit any number of answers, you'd store these in an arraylist as the user could give 1 or 100 answers before getting the question correct, a fixed length array here wouldn't do the job.

Hope that helps

Lee Brindley
  • 6,242
  • 5
  • 41
  • 62