Array In Data Structure

An array is a data structure that consists of a collection of elements of the same data type present in a contiguous memory location.

array-in-data-structure

In the above example, we have ‘Arr’ a one-dimensional array. We can see the elements are stored in a contiguous memory location.

Time complexities for various operations in an array

array-in-data-structure

Using One-Dimensional Arrays in Java

//Declaration of array.
int array[];             
//Allocating memory.
array=new int[10];
//Declaring and allocating memory in one line.
int array[]=new int[10];
//creating an array and initializing with elements.
int array[]={1,2,3,4,5}

//Accessing array 
for(int i=0;i<array.length;i++)
System.out.println(array[i]);

//For-Each loop for sequential access without index.

for( int element:array)
System.out.println(element);

Using Two Dimensional Arrays in Java

int arr[][]=new int[3][3];
//A two dimensional array with elements stored in it.
int arr1[][]={{1,2,3},{4,5,6}};

//Accessing elements from two dimensional array in java.
for(int i=0;i<arr.length;i++)
{
    for(int j=0<j<arr[i].length;j++)  
 	System.out.println(arr[i][j]);
   }

Representation of Two Dimensional array -Arr[4][3] in Memory.

array-in-data-structure

Advantages of using arrays

  1. Easy to access elements using index in constant time.
  2. Using one name for multiple elements of the same type, stored adjacent to each other in memory.
  3. Using arrays, other data structures such as stacks, queues, etc can be implemented.
  4. Easy to use and implement compared to other data structures such as linked lists and trees.
  5.  Matrix representation is done in computer science using arrays.

Disadvantages of using arrays

  1. Can’t allocate memory dynamically (at run time).
  2. Insertion and deletion is costly in an array because elements are stored in the consecutive memory location and shifting operation is costly
  3. If we insert less number of elements then the size of the array, memory is wasted.

Do you know?
Array In Data Structure This article is contribute by Kumar Shivam If you want share your knowledge on Study4Geeks then go to login section.