Quick question here: why not ALWAYS use ArrayLists in Java? They apparently have equal access speed as arrays, in addition to extra useful functionality. I understand the limitation in that it cannot hold primitives, but this is easily mitigated by use of wrappers.
Quick question here: why not ALWAYS use ArrayLists in Java? They apparently have equal
Share
If you need a collection of primitives, then an array may well be the best tool for the job. Boxing is a comparatively expensive operation. For a collection (not including maps) of primitives that will be used as primitives, I almost always use an array to avoid repeated boxing and unboxing.
I rarely worry about the performance difference between an array and an
ArrayList, however. If aListwill provide better, cleaner, more maintainable code, then I will always use aList(orCollectionorSet, etc, as appropriate, but your question was aboutArrayList) unless there is some compelling reason not to. Performance is rarely that compelling reason.Using
Collections almost always results in better code, in part because arrays don’t play nice with generics, as Johannes Weiß already pointed out in a comment, but also because of so many other reasons:All of this together, I rarely use arrays and only a little more often use an
ArrayList. However, I do useLists very often (or justCollectionorSet). My most frequent use of arrays is when the item being stored is a primitive and will be inserted and accessed and used as a primitive. If boxing and unboxing every become so fast that it becomes a trivial consideration, I may revisit this decision, but it is more convenient to work with something, to store it, in the form in which it is always referenced. (That is, ‘int’ instead of ‘Integer’.)