Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Should I always replace Arrays for ArrayLists?

Well, it seems to me ArrayLists make it easier to expand the code later on both because they can grow and because they make using Generics easier. However, for multidimensional arrays, I find the readability of the code is better with standard arrays.

Anyway, are there some guidelines on when to use one or the other? For example, I'm about to return a table from a function (int[][]), but I was wondering if it wouldn't be better to return a List<List<Integer>> or a List<int[]>.

like image 539
iceburn Avatar asked Dec 17 '22 23:12

iceburn


2 Answers

Unless you have a strong reason otherwise, I'd recommend using Lists over arrays.

There are some specific cases where you will want to use an array (e.g. when you are implementing your own data structures, or when you are addressing a very specific performance requirement that you have profiled and identified as a bottleneck) but for general purposes Lists are more convenient and will offer you more flexibility in how you use them.

Where you are able to, I'd also recommend programming to the abstraction (List) rather than the concrete type (ArrayList). Again, this offers you flexibility if you decide to chenge the implementation details in the future.

To address your readability point: if you have a complex structure (e.g. ArrayList of HashMaps of ArrayLists) then consider either encapsulating this complexity within a class and/or creating some very clearly named functions to manipulate the structure.

like image 195
mikera Avatar answered Dec 19 '22 13:12

mikera


Choose a data structure implementation and interface based on primary usage:

  • Random Access: use List for variable type and ArrayList under the hood

  • Appending: use Collection for variable type and LinkedList under the hood

  • Loop and process: use Iterable and see the above for use under the hood based on producer code

Use the most abstract interface possible when handing around data. That said don't use Collection when you need random access. List has get(int) which is very useful when random access is needed.

Typed collections like List<String> make up for the syntactical convenience of arrays.

Don't use Arrays unless you have a qualified performance expert analyze and recommend them. Even then you should get a second opinion. Arrays are generally a premature optimization and should be avoided.

Generally speaking you are far better off using an interface rather than a concrete type. The concrete type makes it hard to rework the internals of the function in question. For example if you return int[][] you have to do all of the computation upfront. If you return List> you can lazily do computation during iteration (or even concurrently in the background) if it is beneficial.

like image 42
Alain O'Dea Avatar answered Dec 19 '22 12:12

Alain O'Dea