Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What basically is RandomAccess? Why we use RandomAccess?

I was studying collections in java in between I got stuck a point that some classes like ArrayList implements RandomAccess too while some classes don't. I want to know that why this interface is implemented and what its benefit? What would happen if I use this Interface in my class?

like image 929
Asheesh Sahu Avatar asked Jul 04 '18 16:07

Asheesh Sahu


1 Answers

Random Access List vs Sequential List

Random Access List is a list where you can access any random data in a constant and a faster pace whereas sequential list is where you have to iterate sequentially through all the item before it, to access any particular item.

As in the below graphical image, you can see that in first example, if you want to access 9, you can directly get the values using index whereas in the second image, the data can not be accessed randomly and needs to be iterated through 23 -> 3 -> 17 -> 9 or 42 -> 9 and hence time in accessing any value in the second case is not constant and differs for each value.

enter image description here

Why RandomAccess interface is implemented?

Introduced as part of JDK 1.4, it is a marker interface which indicates that the class implementing it takes constant and fast time in accessing any random data in list.

What is the benefit?

Any implementation of the algorithm can check if the current list is a child of Random Access and accordingly ensure the best performance for random access or sequential access.

Below is one great example from one blog which explains one of the usage in a great way:

Object o;
if (listObject instanceof RandomAccess)
{
  for (int i=0, n=list.size(); i < n; i++)
  {
    o = list.get(i); // directly get the object as list implements Random access
    //do something with object o
  }

}
else
{
  Iterator itr = list.iterator();
  for (int i=0, n=list.size(); i < n; i++)
  {
    o = itr.next(); // Use iterator to get values sequentially as random access 
                    //  is not fast for this list and hence does not implement RandomAccess
    //do something with object o

  }
}

What would happen if I use this Interface in my class?

Same will happen as happens when you implement any other marker interface. It just gives an indication to other class as what can be expected from the class implementing it.

You can also refer Java docs to understand more about it.

like image 184
Aman Chhabra Avatar answered Nov 14 '22 22:11

Aman Chhabra