What are the primary differences between arrays and Arraylists?

Difference between Array and ArrayList

In Java, array and ArrayList are the well-known data structures. An array is a basic functionality provided by Java, whereas ArrayList is a class of Java Collections framework. It belongs to java.util package.

Array vs ArrayList in Java

Let us discuss the concept of the arrays and ArrayList briefly in the header to incorporate the understanding in java programs later landing onto the conclusive differences between them. As we all are aware of that arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already aware of using ArrayList over arrays despite knowing the differences between these two. Now moving ahead even with ArrayList there comes a functionality to pass the type of datatype of elements that are supposed to be stored in the ArrayList be it an object, string, integer, double, float, etc.

Note: As a side note, ArrayList in Java can be seen as similar to vector in C++.

Methods of Creating Arrays

In Java, the following are two different ways to create an array.

  1. Simple fixed-sized arrays
  2. Dynamically sized arrays
int arr[] = new int[10]

Syntax: Declaring a static array array



It can be further defined by two types:

  • Type 1: Declaring and initializing at the same time
  • Type 2: Declaring than initializing elements later.

Type 1

Type array_name [array_size] ; Type array_name = { Element1, Element2, Element3, Element4,...., ElementN } ; // It is preferable if we have very limited array elements

Type 2

int arr [100] ; // This does means we are declaring a memory block named 'arr' // which is containing continuous 100 block associated in it

Note: arr[0] returns the first element of the array so it does mean that if we try to print out arr[0] then we will get Element1. It is very important statement and is left unveiliable when it comes to deep understanding of memory storage in arrays.

Now let us dwell on the next concept of ArrayList that is as follows

Syntax: Declaring an Arraylist

Arraylist al = new ArrayList ; // Here Type is the type of elements in ArrayList to be created

Note: ArrayList in Java [equivalent to vector in C++] having dynamic size. It can be shrunk or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package.

Now let us illustrate examples with the help of differences between Array and ArrayList

Base 1: An array is a basic functionality provided by Java. ArrayList is part of the collection framework in Java. Therefore array members are accessed using [], while ArrayList has a set of methods to access elements and modify them.

Example:

Java




// Java program to demonstrate differences between
// Array and ArrayList
// Importing required classes
import java.util.ArrayList;
import java.util.Arrays;
// Main class
class GFG {
// Main driver method
public static void main[String args[]]
{
// Input array
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
// Printing first element of array
System.out.println[arr[0]];
// ArrayList
// Creating an arrayList with initial capacity
// say bi it 2
ArrayList arrL = new ArrayList[2];
// Adding elements to ArrayList
// using add[] method
arrL.add[1];
arrL.add[2];
// Printing alongside accessing
// elements of ArrayList
System.out.println[arrL.get[0]];
}
}
Output 1 1

Base 2: The array is a fixed-size data structure while ArrayList is not. One need not mention the size of the ArrayList while creating its object. Even if we specify some initial capacity, we can add more elements.

Example:

Java




// Java program to demonstrate differences between
// Array and ArrayList
// Importing required classes
import java.util.ArrayList;
import java.util.Arrays;
// Main class
class GFG {
// Main driver method
public static void main[String args[]]
{
// Normal Array
// Need to specify the size for array
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
// We cannot add more elements to array arr[]
// ArrayList
// Need not to specify size
// Declaring an Arraylist of Integer type
ArrayList arrL = new ArrayList[];
// Adding elements to ArrayList object
arrL.add[1];
arrL.add[2];
arrL.add[3];
arrL.add[4];
// We can add more elements to arrL
// Print and display Arraylist elements
System.out.println[arrL];
// Print and display array elements
System.out.println[Arrays.toString[arr]];
}
}
Output [1, 2, 3, 4] [1, 2, 3]

Base 3: An array can contain both primitive data types as well as objects of a class depending on the definition of the array. However, ArrayList only supports object entries, not the primitive data types.

Note: When we do arraylist.add[1] than it converts the primitive int data type into an Integer object which is as illustrated in below example

Example:

Java




import java.util.ArrayList;
class Test
{
public static void main[String args[]]
{
// allowed
int[] array = new int[3];
// allowed, however, need to be initialized
Test[] array1 = new Test[3];
// not allowed [Uncommenting below line causes
// compiler error]
// ArrayList arrL = new ArrayList[];
// Allowed
ArrayList arrL1 = new ArrayList[];
ArrayList arrL2 = new ArrayList[];
ArrayList arrL3 = new ArrayList[];
System.out.println["Successfully compiled and executed"];
}
}
Output Successfully compiled and executed

Base 4: Since ArrayList can’t be created for primitive data types, members of ArrayList are always references to objects at different memory locations [See this for details]. Therefore in ArrayList, the actual objects are never stored at contiguous locations. References of the actual objects are stored at contiguous locations.

On the other hand, in the array, it depends whether the array is of primitive type or object type. In the case of primitive types, actual values are contiguous locations, but in the case of objects, allocation is similar to ArrayList. Java ArrayList supports many additional operations like indexOf[], remove[], etc. These functions are not supported by Arrays.

We have implemented and seen the differences between them as perceived from outputs. Now let us wrap up the article by plotting conclusive differences in a tabular format a shown below as follows:

Base Array ArrayList
Dimensionality It can be single-dimensional or multidimensional It can only be single-dimensional
Traversing Elements For and for each generally is used for iterating over arrays Here iterator is used to traverse riverArrayList
Length length keyword can give the total size of the array. size[] method is used to compute the size of ArrayList.
Size It is static and of fixed length It is dynamic and can be increased or decreased in size when required.
Speed It is faster as above we see it of fixed size It is relatively slower because of its dynamic nature
Primitive Datatype Storage Primitive data types can be stored directly unlikely objects Primitive data types are not directly added unlikely arrays, they are added indirectly with help of autoboxing and unboxing
Generics They can not be added here hence type unsafe They can be added here hence makingArrayList type-safe.
Adding Elements Assignment operator only serves the purpose Here a special method is used known as add[] method

This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above




Article Tags :
Java
Java - util package
Java-Array-Programs
Java-ArrayList
Java-Arrays
Java-Collections
Java-List-Programs
Practice Tags :
Java
Java-Collections
Read Full Article

Difference between Array and ArrayList

• Categorized under Software | Difference between Array and ArrayList

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.

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 ArrayList’s 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.

Difference between Array and ArrayList

In case you have been confused about the difference between Array and ArrayList, then what follows is undoubtedly for you.Both are used for storing elements which can be objects. Arrays have a fixed length whereas ArrayList has a variable length.

In this post, we will look into both these data structures in detail and compare them too.

ArrayList vs. Array: A comparison chart

Basis of DifferentiationArrayArrayList
Size of data structureAn array contains a data structure of fixed length. The size of the Array cannot be changed once the object has been defined. It is static.The size of an ArrayList is dynamic. The elements/ items in the data structure can be modified to change the size of the object as and when required.
Resizing propertyAs an Array length is static across the program, its size will remain unchanged.The size of an ArrayList is capable of changing dynamically based on the capacity and load it has to function with.
Insertion and storage of elementsThe assignment operator is put to use for the storage of elements.The add[] attribute is utilized for the insertion of elements in an ArrayList.
Nature of datatypesAn Array can store primitive data types as well as other objects that are of the different or same data type.ArrayLists can only store object types. They are not able to contain primitives.
GenericsGenerics are not compatible with Arrays.ArrayLists allow the use of Generics.
Multi-dimensional natureArrays are multi-dimensional.ArrayLists are single-dimensional.
Storage in contiguous memory locationsAn Array is a native programming component wherein the elements are contained in adjacent memory locations.
An ArrayList belongs to a class belonging to Java’s collections framework. Here, the objects are incapable of being contained in contiguous locations.
Determination of lengthThe Length variable is responsible for determining an Array’s length.The length of an ArrayList is set by the Size [] method.
Memory space consumedArrays take more memory for the storage of specified objects or elements.
ArrayLists take less memory space for storing objects or elements.
IterationIterating across an Array takes lesser time than what it does in the case of ArrayLists.
Iterating across an ArrayList takes more time, and the performance is slower.

Video liên quan

Bài mới nhất

Chủ Đề