Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

collection questions

Hi,
i have below collection questions. please advise



why array list implements RandomAccess and cloneable serializeable
why RandomAccess in marker interface and how is interface useful without methods
which collection is good for retrieval,insertion, deletion etc
Avatar of dpearson
dpearson

From the docs:

public interface RandomAccess
Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.

Like it says, the idea is you can mark a collection as being quick to access things in a random order.
So you can get to element 100 as quickly as you can reach element 2.

So when would that not be true?  Here's another List implementation that uses a simple linked list:

public class MyLinkedList {
    private int m_Value ;
    private MyLinkedList m_Next ;

    public MyLinkedList(int value, MyLinkedList next) {
        m_Value = value ;
        m_Next = next ;
    }
}

Open in new window


MyLinkedList a = new MyLinkedList(10, null) ;
MyLinkedList b=  new MyLinkedList(20, a) ;

Open in new window


I hope you can see that
b is the list "20, 10, null".        (b has value 20, with m_Next set to a that has value 10).

To look up the values in this list the code would be:

public Integer getIndex(MyLinkedList list, int position) {
     while (position != 0 && list != null) {
         position-- ;
         list = list.m_Next ;
     }
     if (list == null)
        throw new ArrayIndexOutOfBoundsException("List doesn't have an element in position " + position) ;

     return list.m_Value ;
}

Open in new window


Since that requires a loop, it will be slower for the 100th element than the 1st, so not random access.

Make sense?

Doug
Avatar of gudii9

ASKER

b is the list "20, 10, null".        (b has value 20, with m_Next set to a that has value 10).

i did not understand above line. please advise
so this is example which is not implementing random access so it is slow right?

b has a  so to reach a through b requires more loop like that to go to deeper elements like 100 deep. so without randome access it is slow right.
please advise my understanding is correct on what you mentioned
ASKER CERTIFIED SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial