Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ArrayList implement RandomAccess Interface?

ArrayList implements RandomAccess interface. RandomAccess interface has no methods. When I checked LinkedList it does not implement RandomAccess interface.

So in case of ArrayList, what is the point of implementing it?

like image 821
GD_Java Avatar asked Jan 01 '14 15:01

GD_Java


People also ask

What is random access memory in ArrayList?

In computer science, random access (more precisely and more generally called direct access) is the ability to access an item of data at any given coordinates in a population of addressable. Wikipedia. The ArrayList provide API to access any element using method get(int) . The int is the index of item in Object[] .

What is random access in collection?

Random-access collections can move indices any distance and measure the distance between indices in O(1) time. Therefore, the fundamental difference between random-access and bidirectional collections is that operations that depend on index movement or distance measurement offer significantly improved efficiency.

Which is faster ArrayList or LinkedList?

LinkedList is faster than ArrayList while inserting and deleting elements, but it is slow while fetching each element.

What is the difference between ArrayList and LinkedList?

ArrayList internally uses a dynamic array to store its elements. LinkedList uses Doubly Linked List to store its elements. ArrayList is slow as array manipulation is slower. LinkedList is faster being node based as not much bit shifting required.


2 Answers

Interfaces with no methods are called marker interfaces in Java.

As per the JavaDoc of RandomAccess:

Marker interface used by List implementations to indicate
that they support fast (generally constant time) random access.

For more information check the two JavaDoc pages.

http://docs.oracle.com/javase/6/docs/api/java/util/RandomAccess.html

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

like image 107
peter.petrov Avatar answered Sep 23 '22 01:09

peter.petrov


RandomAccess interface has no method

This is called a marker interface and is a design pattern called marker interface pattern.

When I checked LinkedList it does not implement RandomAccess interface. So in case of ArrayList what is the point of implementing it?

Because random access in a LinkedList is O(n), while it's O(1) in an ArrayList.

It's stated in the doc :

The best algorithms for manipulating random access lists (such as ArrayList) can produce quadratic behavior when applied to sequential access lists (such as LinkedList)

like image 35
user2336315 Avatar answered Sep 19 '22 01:09

user2336315