Open In App

How to Implement an Array with Constant-Time Random Access in Java?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, random access in arrays requires direct index-based addressing, it usually takes constant time, or O(1). Standard arrays in Java provide random access that is constant in time.

In this article, we will learn how to implement an array with constant-time random access in Java.

Constant-Time Random Access

The term constant-time random access means accessing an element by index takes the same amount of time irrespective of the size of the array.

  • Using index-based addressing is the essential idea for obtaining constant-time random access.
  • Arrays in Java are stored in contiguous memory locations, and accessing an element in an array is easy i.e. by calculating its index.

Program to Implement an Array with Constant-Time Random Access in Java

To illustrate constant-time random access in arrays, below we have implemented a basic Java program:

Java




// Java program to implement an array
// With constant-time random access
import java.util.Arrays;
  
// Driver Class
public class ConstantTimeRandomAccess 
{
    // Main function
    public static void main(String args[]) 
    {
        // Create an array of integers
        int[] numbers = {20, 40, 60, 60, 100};
  
        // Access elements using indices (constant-time random access)
        int elementAtIndex2 = numbers[2];
        int elementAtIndex4 = numbers[4];
  
        // Print the results
        System.out.println("Element at index 2: " + elementAtIndex2);
        System.out.println("Element at index 4: " + elementAtIndex4);
    }
}


Output

Element at index 2: 60
Element at index 4: 100


Explanation of the Program:

In the above program,

  • An array of integers named numbers is created and initialized with values.
  • Elements of the array are accessed index-based, and it demonstrates constant-time random access.
  • The values of elements at indices 2 and 4 are printed to the console.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads