I find that I can do almost any thing easily and with more control by using an ArrayList
than by using an array in my day-to-day coding.
So I am asking:
ArrayList
instead?ArrayList
?Using one over another definitely impacts over performance and efficiency, though it might me very small. Also implementation of JVM
impacts a lot. However, adding and fetching entries from arrays
are always quicker than in List
.And if you are certain about the size of the array
you need, you might be saving little memory too while using array.
However, List
gives you more flexibility in modifying your contents, basically lots of methods to manipulate the data. It fully supports generics
.
Since arrays are covariant
and Generics are invariant
, Arrays and Generics don't mix
so Joshua Bloch
recommends use of List over array in his book Effective Java II
chapter 25. I will definitely follow his advice and recommend you to use List as well instead of array.
When choosing specifically between an Array and an ArrayList, your first consideration should be whether the length of the container will need to change or not. If it does, use an ArrayList, but even if it doesn't, I would still go so far as to say that you should use an ArrayList. The reason for this is that the performance overhead incurred by using an ArrayList is generally not significant enough to warrant substituting it with an Array unless you absolutely know that performance is going to be an issue.
In general I would argue that it is a better idea to use a List over an Array in most situations. Arrays do offer slightly higher performance due to the reduced overhead. However, since List is an interface, there are a number of specific implementations available (ArrayList, LinkedList, etc.) which gives you as well as the client code more flexibility.
For example, if you were to write a method that performs some computation and returns a List, the client code would only be able to assume that the List being returned is constructed in accordance to its definition in the Java documentation.
For example, in the client code you might find something like:
List<T> list = foo.getList();
If the method getList() currently returns an ArrayList, and you wanted to change its behaviour such that it now returns a LinkedList, you would be able to do that without worrying about breaking the client code which uses your method as it is only assuming that it will receive some implementation of a List but not any specific one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With