[Solved] What is the better Way to Store fixed no of data in Java? (Array vs ArrayList) [closed]


ArrayLists will have an ever so slightly higher overhead than an array. This is because an ArrayList is just a wrapper for an array with a few convenience methods added. Though if you know exactly how many elements you will ever have then ArrayList doesn’t add much.

The biggest advantage of having an array over an ArrayList (at least in Java), is the cleaner syntax. eg.

myArray[0] = x;
// as opposed to
myList.set(0, x); 
// personally I can never remember the order for the arguments and I have to check

Adding all the elements to another list

One possible advantage to ArrayLists is being able to easily add all the elements in an ArrayList to another list.

anotherList.addAll(myList);

However, the same can easily be accomplished by using the Collections util class.

Collections.addAll(anotherList, myArray);

Immutability

One problem is that arrays are mutable (element values can be changed), but you may only want to present a immutable view of your collection of elements to classes outside your own class. Here lists can be useful again.

List<E> readOnly = Collections.unmodifiableList(myList);

But in this case also Arrays can still easily be used to to back an immutable list.

List<E> readOnly = Collections.unmodifiableList(Arrays.toList(myArray));

Synchronized access

Finally, and most importantly, you can make use of the Collections class to make your Lists synchronized.

List<E> syncedList = Collections.synchronizedList(myList);

You could wrap your array in a list and make access synchronized, but then you’d still have to use access via the list, so there wouldn’t be much point in having an array.

Final word – Personal preferences

In general though, the whole thing comes down to preference. What is your personal preference, do you prefer working with arrays or Lists? Personally I prefer lists because they work better with the rest of the collections API and making a generic Lists is easy, making generic arrays is a real pain.

List<E> list = new ArrayList<E>(); // easy
E[] array = new E[]; // compilation error

1

solved What is the better Way to Store fixed no of data in Java? (Array vs ArrayList) [closed]