ArrayList in Java
Many people wrongly assume that array and ArrayList have no significant differences and both mean the same. This article will let you identify and draw a fine line between both of these concepts. Before figuring out the differences between them, let us first try to understand each of the concepts elaborately.
What is an array in java?
An array is a linear structure database that is created dynamically. It contains more than one value of the same data type. The memory allocated for these values in an array is contagious. The size of an array cannot be altered after its creation.
Syntax for java array:
int array[] = new int[size];
The array that we create would have the fixed size. Therefore, if we try to add more elements to it, it throws ArrayIndexOutOfBoundsException. Below is a semantics for array.
int arr[] = new int[2]; //the size of the array is 3 (0,1,2) arr[0] = 5; // adding elements to the array arr[1] = 26; arr[2] = 17;
Methods to create an array:
In Java, we can imply two different ways to create an array:
1. Simple fixed-size arrays
2. Dynamically sized arrays
We can create a static array in the following two ways:
1. Declaring and initializing simultaneously:
The syntax to create an array in this type is:
Type array_name[array_size]; Type array_name = {element1, element2, element3, …. element N};
This array declaration would be convenient when the size of the array is small.
2. Declaring and initializing the elements later:
int arr[100]; // here, the array can hold up to 101 elements that can be initialized later.
Java ArrayList:
It is a class that belongs to the collection framework. This framework implements List<E>, Iterable<E>, Collection<E>, Cloneable, Serializable and RandomAccess interfaces. It also extends the Abstract<E> class.
Syntax to create Java ArrayList:
ArrayList <Type> ArrayList = new Arraylist<Type>();
The concept of ArrayList is backed by an array in Java. Operations like resizing slow down the performance of an array. This is due to the process of copying content from an old array to a new one. This involves calling the method System.arraycopy(sec, srcPos, dest, destPos, length).
It sores only objects and not primitive types. In the presence of any such primitive type, it is automatically converted to an object.
For example,
ArrayList <Integer> list = new ArrayList <Integer>(); // it is an object of Arraylist arrayObj.add(23) // here, trying to add an integer primitive into the ArrayList
At this stage, the JVM automatically converts it into Integer object via auto-boxing:
ArrayList arrayObj = new ArrayList(); arrayObj(new Integer(23)); // it converts & adds to ArrayList object
What are the common similarities between an Array and an ArrayList?
Though the two concepts vary in certain aspects, there are a few similarities between them. Let’s take a look at them.
- Java Array and ArrayList are used to store elements.
- They store null values.
- Duplication of values is allowed.
- The order of the elements is not given importance.
Sample program for java array creation:
public class FirstCode{ public static void main(String args[]){ int arr[] = new int[3]; arr[0]=23; arr[1]=17; arr[2]=5; for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
Output:
17
5
Sample program for ArrayList in Java:
import java.util.*; public class FirstCode{ public static void main(String args[]){ List<Float> list = new ArrayList<Float>(); list.add(23.2); list.add(17.8); list.add(5.2); for(Float f:list) { System.out.println(f); } } }
Output:
17.8
5.2
Basis
|
Array | ArrayList |
Definition | It is a dynamically created object. It acts as a container to hold values of the same data type. The memory is contiguously allocated.
|
It is a class of Java collections framework. Some of the popular classes present here are Vector, HashTable and HashMap. |
Static/ Dynamic | It has a static size. | The size is dynamic. |
Initialization | The size of the array is a primary requirement while initializing an array.
|
An instance of an array can be created without denoting its size. |
Resizable | Due to its fixed size, an array cannot be resizable.
|
ArrayList can be resized as its’ size is variable. |
Primitive/ Generic type | It can store primitive and object types.
|
The primitive type cannot be directly stored in an ArrayList. It is converted to an object before storage.
|
Performance | Comparatively fast performance due to fixed size. | ArrayList performs comparatively slow due to resizing operations. |
Iterating values | We can use for loop and for each loop for array iteration. | We use an iterator for iteration here.
|
Type-safety | Generics cannot be used as the array is not of a convertible type.
|
It stores only generic type. Therefore, it is type-safe. |
Length | The variable ‘length’ provides the array’s length.
|
The size() method present in it gives the size of the Arraylist. |
Single/ multidimensional | It can be multi-dimensional. | It is single-dimensional. |
Adding Elements | The assignment operator allows us to add the elements in an array.
|
The add() method allows us to add the elements in an ArrayList. |
Now, you might have a clear idea of the differences between the concept of array and ArrayList in Java. Let us dive deep into our next topic Array class in Java.
You might wonder, what is the necessity of a separate class named array? We already know that most of the operations can be performed using normal arrays in Java. Further, we will discuss on the special features and methods present in the array class.
Syntax for array class declaration:
public class Arrays extends Object
Syntax to use array:
Arrays.<function name>;
Where is the array class generally helpful?
There are many tasks that are predominantly performed by loops in Java. Some of such tasks include:
- Array sorting
- Searching in an Array
- Adding elements to an array
Whereas the array class contains various static methods that accomplish these tasks. Below are such methods along with their description:
Methods | Description |
asList() | It returns a fixed-sized list that is present as a backup in specific arrays. |
binarySearch() | It uses the binary search algorithm to search for an element in the array. |
binarySearch(array, fromIndex, toIndex, key, Comparator) | It uses the Binary search algorithm to search a specified range of the array. |
Compare(array1, array2) | It compares the given two arrays lexicographically. |
copyOf(originalArray, newLength) | It copies an array and performs truncating or padding to attain the specified length. |
copyOfRange(originalArray, fromIndex, endIndex) | It copies the particular range of the given array into another array. |
deepEquals(Object[]a1, Object[]a2) | It returns true if the given arrays are deeply equal to each other. |
deephashCode(Object[] a) | It returns has code according to the deep contents present in the array. |
deepToString(Objecct[] a) | It returns the String representation of “deep contents” that belongs to the arrays. |
equals(array1, array2) | It checks if the given two arrays are equal to each other. |
fill(originalArray) | It fills the value to each array index. |
hashCode(originalArray) | It returns an Integer hashCode of the array. |
mismatch(array1, array2) | It encounters the first unmatched element in the two arrays and returns it. |
parallelPrefix(originalArray, fromIndex, endIndex, functionalOperator) | It performs parallelPrefix for the specified range of array with the functional operator. |
parallelPrefix(originalArray, operator) | It performs parrallelPrefix for the entire array with a functional operator. |
parallelSetAll(originalArray, functionalGenerator) | It arranges all the elements parallelly using the generator function. |
parallelSort(originalArray) | Sorts the array with parallel sort. |
setAll(originalArray, functionalGenerator) | It sets all the elements in the array using the generator function. |
sort(originalArray) | It sorts the entire array in ascending order. |
sort(T[] a, int fromIndex, int yoIndex, Comparator<super T> c) | It sorts the array of specified range of the particular array elements. |
sort(T[] a, Comparator <super T> c) | It sorts the array in an order as mentioned by the comparator. |
spliterator(originalArray) | It returns a spliterator that includes all the mentioned arrays. |
spliterator(originalArray, fromIndex, endIndex) | It returns a spliterator that covers a particular range of the mentioned arrays. |
stream(originalArray) | It returns a sequential stream |
toString(originalArray) | It returns a string representation of the contents present in the array. |
Sample program using java asList() method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,2,3,6,2}; System.out.println(“The Given array list is: ”+Arrays.asList(sampleArr)); } }
Output:
Sample program using java binarySearch() method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,23,6,12}; Arrays.sort(sampleArr); int intKey = 23; System.out.println(intKey + “is present at index: ”+Arrays.binarySearch(sampleArr, intKey)); } }
Output:
Sample program using java binarySearch(array, fromIndex, toIndex, key, Comparator) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; Arrays.sort(samplearr); Int intKey = 16; System.out.println(intKey + “is present at index: ”+ Arrays.binarySearch (sampleArr, 1, 3, itnKey)); } }
Output:
Sample program using java compare(array1, array2) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,2,3,6,2}; int sampleArr2[] = {1,2,5,6}; System.out.println(“The index at where the integers change first: ”+Arrays.compare(sampleArr, sampleArr2)); } }
Output:
Sample program using java compareUnsigned(array1, array2) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,2,3,6,2}; int sampleArr2[] = {1,2,5,6}; System.out.println(“The index at where the integers change first: ”+Arrays.compareUnsigned(sampleArr, sampleArr2)); } }
Output:
Sample program using java copyOf(originalArray, newLength) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array: ”+Arrays.toString(sampleArr)); System.out.println(“The new array after copying: ”); System.out.println(“The array is: ”+Arrays.toString(Arrays.copyOf(sampleArr,8))); } }
Output:
The new array after copying:
The array is: [1,21,3,16,12,0,0,0]
Sample program using java copyofRange(originalArray, fromIndex,endIndex) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array: ”+Arrays.toString(sampleArr)); System.out.println(“The new array after copyOfRange: ”); System.out.println(“The array is: ”+Arrays.toString(Arrays.copyOfRange(sampleArr,1,4))); } }
Output:
The new array after copyOfRange:
The array is: [21,12]
Sample program using java deepEquals(Object[] a1,Object[] a2) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[][] = {{1,21,3,16,12}}; int sampleArr2[][] = {{1,21,3,16,12}}; System.out.println(“The integer array on comparison: ” +Arrays.deepEquals(sampleArr, sampleArr2)); } }
Output:
Sample program using java deepHashCode(Object[] a) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[][] = {{1,21,3,16,12}}; System.out.println(“The integer array: ”+Arrays.deepHashCode(sampleArr)); } }
Output:
Sample program using java deepToString(Object[] a) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[][] = {{1,21,3,16,12}}; System.out.println(“The integer Array: ”+Arrays.deepToString(sampleArr)); } }
Output:
Sample program using java equals(Object[] a1,Object[] a2) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; int sampleArr2[] = {1,21,31}; System.out.println(“The integer array on comparison: ”+Arrays.equals(sampleArr, sampleArr2)); } }
Output:
Sample program using java fill(OriginalArray, fillValue) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,23,3,16,12}; int sampleKey = 23; Arrays.fill(sampleArr, sampleKey); System.out.println(“The integer array on filling: ”+Arrays.toString (sampleArr)); } }
Output:
Sample program using java hashCode(originalArray) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array: ”+Arrays.hashCode(sampleArr)); } }
Output:
Sample program using java mismatch(array1, array2) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; int sampleArr2[] = {1,23,3}; System.out.println(“The element that was a mismatch was found at index: ”+Arrays.mismatch(sampleArr, sampleArr2)); } }
Output:
Sample program using java parallelSort(originalArray) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array is: ”+Arrays.toString (sampleArr)); } }
Output:
Sample program using java sort(originalArray, fromIndex, endIndex) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; Arrays.sort(sampleArr, 1, 3); System.out.println(“The integer array is: ”+Arrays.toString(sampleArr)); } }
Output:
Sample program using java spliterator(originalArray) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array is: ”+Arrays.spliterator(sampleArr)); } }
Output:
Sample program using java spliterator(originalArray, fromIndex, endIndex) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array is: ”+Arrays.spliterator(sampleArr, 1, 3)); } }
Output:
Sample program using java stream(originalArray) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array is: ”+Arrays.stream(sampleArr)); } }
Output:
Sample program using java toString(originalArray) method:
import java.utilArrays; class FirstCode{ public static void main(String args[]){ int sampleArr[] = {1,21,3,16,12}; System.out.println(“The integer array is: ”+Arrays.toString(sampleArr)); } }
Output:
Difference between Array vs ArrayList in Java:
1. Nature:
The length of an array in java is not prone to changes. The declaration of an array’s length becomes fixed during its creation. Therefore, it is static in nature.
Whereas ArrayList is dynamic, and there are chances to resize its length. When an element beyond the specified limit is added to an array, it increases its size automatically.
2. Iterations:
The elements can iterate only using for-loop, while loop and for-each loop in an array. But there is a special facility in ArrayList to iterate the elements. The Iterator and ListIterator classes also achieve the desired result.
There are no limitations to use while, for and for-each loops to iterate an ArrayList. But, the arrays do not support an iterator to accomplish this task. Comparatively, ArrayList has various options than an array to iterate the elements.
3. Supported Operations:
An ArrayList supports various methods like get(), isEmpty(), indexOf(), replaceAll(), removeAll(), clear() and contains(). But there are no such options available in Arrays. This makes ArrayList better as it provides different methods and operations.
Conclusion
Using all these various methods of arrays, you can achieve various results in Java. This article would have been helpful in introducing you to a wide list of in-built methods. It also would have made you aware of all the differences between an array and ArrayList. You can try the sample programs and make use of the available options to attain the desired result effortlessly in Java.