Which class is super class of every class

Which collection classes provide random access of its elements

Answer : RandomAccess interface is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access. Primary purpose of this interface was to allow generic algorithms to alter their behavior and provide good performance when applied to either random or sequential access lists.

All Known Implementing Classes:

ArrayList, AttributeList, CopyOnWriteArrayList, RoleList, RoleUnresolvedList, Stack, Vector

 

Also it is known that distinction between random and sequential access is often uncertain. For example : some of the List implementations provide random access times if they get huge, but constant access times in general practice. Let’s see example below:

package com.javahonk.randomaccess;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RamdomAccessTest {

	public static void main(String args[]) {

	List<String> list = new ArrayList<String>();

	for (int i = 0; i < 50000; i++) {
		list.add("Java");
		list.add("Honk");
	}

	Long startTime = System.currentTimeMillis();
	System.out.println("Start time: " + startTime);

	for (int i = 0, n = list.size(); i < n; i++) {
		list.get(i);
	}

	Long time1 = System.currentTimeMillis();
	System.out.println("Example 1 time in milli: " + (time1 - startTime));

	for (Iterator<String> i = list.iterator(); i.hasNext();) {
		i.next();
	}

	Long time2 = System.currentTimeMillis();
	System.out.println("Example 2 time in milli: " + (time2 - time1));

	for (String string : list) {

	}

	Long time3 = System.currentTimeMillis();
	System.out.println("Example 3 time in milli: " + (time3 - time2));

	if (time2 > time1) {
		System.out.println("Example 1 is faster");
	} else if (time3 > time2) {
		System.out.println("Example 2 is faster");
	} else {
		System.out.println("Example 3 is faster");
	}

	}

}

 

Output:

Start time: 1395082451059
Example 1 time in milli: 2
Example 2 time in milli: 6
Example 3 time in milli: 4
Example 1 is faster

 

Leave a Reply

Your email address will not be published. Required fields are marked *