ArrayList vs array

Array and ArrayList are two of the most prevalent data structures used in Java. The Array needs no introduction as it is one of the first data structures any java programmer learns. ArrayList is another data structure possessing some of the fundamental characteristics of arrays along with some new features. It is part of thecollection frameworkin java, similar to other popular classes likeVector,Hashtableor LinkedList. The ArrayList is a dynamic array that can be resized whenever required. The list created using ArrayList class is nothing but an array of objects.

Table of Contents

  • Array vs ArrayList in Java:
  • Which one to choose?
    • 1. Static VS Dynamic Nature:
    • 2. Fixed vs Variable Length:
    • 3.Type-safety and generic Support:
    • 4.Dissimilar Methods:
    • 5.Type of elements to be stored:
    • 6.Different declarations:
    • 7.Array is Multi-dimensional:
    • 8.Different Iteration processes:
    • 9. Performance:
    • 10. Usability:
  • Conclusion

Array vs ArrayList in Java:

In Java, the standard arrays have a fixed length, so you already know the size of the array from the start. But, in certain scenarios, you may not know what length of the array you will be needing until the run time. Hence, the Collection framework was introduced in the ArrayList class to solve this problem. ArrayList class has constructors that create an array with its initial capacity by default but the capacity of the object of class ArrayList increases automatically when more elements are added to that array. Despite some limitations, Array still holds its grounds. Being part of core Java programming, java provides special syntax and semantics support for extended control over Arrays than Arraylist.

Which one to choose?

Despite the know differences, The Array vs ArrayList quandary is quite common among new java developers. The maindifference between Array and ArrayList in Javais their nature, Array has a static nature whereas ArrayList is dynamic. This basic difference has given birth to the debate of Array vs Arraylist in Java and which one is more efficient than the other.

ArrayList vs array

The answer cannot be simple as both offer some unique features for java developers. It would be a subjective decision based on the requirements of a problem.

Following are 10 points discussing the features offered by an Array and ArrayList and the differences between them. This can help you build a better perspective on the Array vs Arraylist in java debate and provide you with an insightful understanding of the proper use of each of them.

1. Static VS Dynamic Nature:

As already mentioned above, the fundamental difference between Array vs Arraylist is in their nature. Both Array and Arraylist exhibit different natures for storage. When an array is made, the memory is allocated at compile time and the developer would have no control during runtime. On the contrary, Arraylist is based on the practicality of the list data structure. It mimics the features of a list which is a dynamic data structure, thus it has the same nature. It gives an edge to ArrayList as it would be a better choice when it comes to solving dynamic problems.

2. Fixed vs Variable Length:

The one difference between Array and ArrayList in Java that every developer surely knows is that Array is a fixed-length data structure while ArrayList is a variable-lengthCollection class. It means that once an array is declared with a certain size, it is fixed and you cannot change it. Whereas, ArrayList automatically re-sizes itself when it gets full depending upon the capacity and load factor. In retrospect, an ArrayLists capacity grows automatically as new elements are added in it.

The fixed size is the only limitation in arrays. Thus, ArrayList would be a clear choice for developers who are uncertain about the frequency of data at compile-time and want to specify the size at runtime. Despite that, an experienced developer would know how significantly it impacts the performance of the program. However, an ArrayList cannot be a good choice in every situation, especially when there are frequent changes to be made in the size of the ArrayList.

3.Type-safety and generic Support:

Developers can easily ensure type-safety in java using Generics. Another difference in the Java Array vs ArrayList debate is that Arrays do not allow the use of Generics. An Array is a homogeneous data structure; therefore it contains data specific data type. As the data type is already defined in an Array instance, it knows which data it can hold and throws an exception labelled ArrayStoreException in the case of someone attempting to assign a different data type in an array that is not convertible into that data type of Array.

For example, here is a code snippet showing when we will automatically encounter an ArrayStoreException.

1. String temp[] = new String[2]; // an array of string data type is declared 2. temp[0] = new Integer(12); // it will throw ArrayStoreException due to trying to add Integer object in the array.

Since ArrayList is a class, it allows you to use Generics to ensure type-safety. Without using Generics, objects with different data types can be assigned in an ArrayList. This can cause irregularities and will not generate any error even if there is unintentional use of distinct data types. Such an error could be easily missed out by the developer and would have to be handled during quality assurance testing.

Here is an example,

1. List list = new ArrayList(); 2. list.add(5); 3. list.add("5"); // It will not generate any error 4. //With Generics, it is required to specify the type of object we need to s ore. 5. List list = new ArrayList(); 6. list.add(5); 7. list.add("5");// It will generate a compile-time error

4.Dissimilar Methods:

Array and ArrayList can also be differentiated based on the radically different methods offered by both of them, for instance,in calculating the length of Array or the size of ArrayList. Array provides a variable that denotes the length of Array, while ArrayList has a size () method in java that calculates and returns the size of ArrayList. Another example would be that Java provides an add () method to insert an element into ArrayList, whereas for storing an element in Array, it simply requires the use of an assignment operator.

A unique advantage that arraylist offers is that the same add () method can also insert a specific value at a certain position, moving all the values ahead by one. But this will require you to write some lines of code if you want to do it using a standard array.

See the code snippet mentioned below,

1. int arr [] = new int[3]; 2. arrayLength = arr.length ; //the length of the array will be assigned to the variable arrayLength 3. arrlist = new ArrayList(); 4. arrlist.add(12); 5. arrlist.size(); //it will return 1 as only 1 element has been added in arraylist.

5.Type of elements to be stored:

Another point in Array vs ArrayList is that ArrayList cannot contain primitive data types (like int, float, double), it can only contain Objects. In comparison, Array can store both primitive data types as well as Objects in Java.

There is a method called Autoboxing that allows storing primitive data types in ArrayList but it merely gives an impression of it. It simply converts the data into an Object before storing it in an ArrayList.

For instance, suppose we have ArrayList called arrList,

1. arrList = new ArrayList(); 2. arrList.add(23); // attempt to add 23 (an integer value) in arraylist. Although it seems like storing an integer in arraylist but it will be converted into an object before storing.

Using Autoboxing, JVM implicitly converts the primitives to equivalent objects, ensuring that only objects are added into an ArrayList. Thus, the above step works like this:

ArrayList object.add( new Integer(23)); // Converted int primitive into an Integer object and then it is added to arrList.

6.Different declarations:

Both Array and ArrayList have a very different declaration process. As Array has a fixed variable length, it needs to specify the size at the time of declaration along with the data type.

int[] numbers = new int[10];On the contrary, ArrayList can be easily declared without specifying the size or datatype, as Java will create ArrayList with the default size and it can later be resized as per requirement.ArrayList numList = new ArrayList();

7.Array is Multi-dimensional:

The array is commonly known for multi-dimensions. one dimensional (1D), two dimensional (2D) even three dimensional (3D) arrays can be declared for storing various types of data. On the other hand, ArrayList is always single dimensional. Arraylist is based upon the properties of a list due to which it does operate beyond one dimension.

8.Different Iteration processes:

ArrayList class offers an iterator to iterate through the elements in a declared ArrayList, whereas a loop is used (mainly FOR loop) to iterate through arrays whether it is a single or multi-dimensional array. Using FOR loop could give more control if applied with a proper counter as compared to an iterator.

9. Performance:

Performance is one of the most important aspects to be considered while comparing Array vs ArrayList in java. It can significantly affect the decision of a developer while choosing between an Array or ArrayList to implement in a program.

In terms of performance, both Array and ArrayList would provide similar performance when considering the time taken for adding or retrieving the elements if you know the index. However, this is the only point where performance is the same.

Although ArrayList seems faster, overall, it does not amount to much difference.. Internally, an ArrayList is made using Arrays in Java, and all resize operations involve creating another array with a new size, transferring all the data into that implicitly and then renaming the newly created Array. This frequent memory allocation process is expensive and can significantly affect performance if you are dealing with a lot of data.

Methods like resize () and add () could slow down the program if they are used frequently with a lengthy ArrayList. In that case, if you want to use ArrayList, try to keep the use of resizing methods to a minimum or use Array instead. Creating an array of a bigger size at compile time could be a better option instead of frequent memory allocations in ArrayList.

10. Usability:

Though ArrayList can be slower than standard arrays in terms of performance, it is easier to implement than Arrays. The flexibility with length, dynamic nature and implicit processes for resizing makes it simpler and easy to develop logic, especially for new developers. Where an operation can be performed by just a single method in ArrayList, it requires multiple lines of codes to be written for implementing it using an array.

Conclusion

These are some prominent points about Array vs ArrayList in Java. Both Array and ArrayList are the core concept of Java, and any Java developer aiming to become an expert in this field must be familiar with all these points and should be able to understand the difference between Array and ArrayList in terms of functionality, practicality and performance.

See Also: AES Encryption and Decryption in Java

The ArrayList overcomes the only limitation arrays have in Java, which is that an Array can not grow in size once it is created. However, by using an ArrayList, the performance can be greatly affected. Whereas ArrayList is easier to implement, the use of arrays provides more control over the data. Arrays also allow primitive as well as objects, where ArrayList only allows objects. Both Array and ArrayList offer some great features that cannot be overlooked, and it is totally up to a developer which data structure they find better and more practical in this array vs arraylist in java debate.

ArrayList vs array