Open In App

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

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

Note: The term constant-time random access means accessing an element by index, it 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.

Array with Constant-Time Random Access Implementation

Java
import java.util.Arrays;

public class ConstantTimeRandomAccess 
{
    public static void main(String args[]) 
    {
        int[] arr = {20, 40, 60, 60, 100};

        // Access elements using indices (constant-time random access)
        int ele2 = arr[2];
        int ele4 = arr[4];

        // Print the results
        System.out.println("Element at index 2: " + ele2);
        System.out.println("Element at index 4: " + ele4);
    }
}

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

Explanation of the 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.

Next Article
Practice Tags :

Similar Reads