How to Implement an Array with Constant-Time Random Access in Java?
Last Updated :
15 Feb, 2024
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
import java.util.Arrays;
public class ConstantTimeRandomAccess
{
public static void main(String args[])
{
int [] numbers = { 20 , 40 , 60 , 60 , 100 };
int elementAtIndex2 = numbers[ 2 ];
int elementAtIndex4 = numbers[ 4 ];
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.
Share your thoughts in the comments
Please Login to comment...