Array Data Structure in Java

Published by Vignesh M on

An Array is a data structure to store elements of same type. Each element can be accessed by index. Hence random access is possible using Array.

An array of 10 elements with index starting at 0

Arrays can be of any dimensions. Single and two dimensional arrays are commonly used. Two dimensional arrays are used for mathematical calculations (for example, Matrix).

Several abstract data structures like Hashtable, ArrayList uses arrays as the underlying data structure.

Working with Arrays 

To initialize an array the size has to be given up front.

Elements can be added to an array using the numeric index.

Accessing the arrays can done using the random index. Hence the operation is very fast and is O(1) complexity. However searching for a specific element in an array is not going to be so efficient. The elements has to iterated over to complete the search. Hence it is O(N) linear time complexity.

Similarly, copying elements of an array to an another array is also going to be O(N) Linear time complexity. Since entire array has to iterated over and copy each element to new array.

Summary

Array data structure is a good choice when,

  • The number of elements to be added is well known.
  • Only the same data type has to be stored together.
  • The elements are going to be added and retrieved using the random index value. It is O(1) complexity.

Array is not so efficient when,

  • The number of elements to be added is not known.
  • There is a need to create array of bigger size. Each value has to be copied one by one.
  • Constructing a new array from an existing one is O(N) operation.
  • Specific element has to searched. Search operation in Array is O(N) complexity.
References

Array representation image : https://docs.oracle.com/javase/tutorial/figures/java/objects-tenElementArray.gif

 


Vignesh M

Java developer , AWS Certified Solutions Architect Associate and Cloud technology enthusiast. Currently working for Hexaware technologies. He believes that knowledge increases by sharing not by saving.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.