RandomAccess在类Collections的shuffle()方法中的使用:(jdk源码如下)

 /**
* Randomly permute the specified list using the specified source of
* randomness. All permutations occur with equal likelihood
* assuming that the source of randomness is fair.<p>
*
* This implementation traverses the list backwards, from the last element
* up to the second, repeatedly swapping a randomly selected element into
* the "current position". Elements are randomly selected from the
* portion of the list that runs from the first element to the current
* position, inclusive.<p>
*
* This method runs in linear time. If the specified list does not
* implement the {@link RandomAccess} interface and is large, this
* implementation dumps the specified list into an array before shuffling
* it, and dumps the shuffled array back into the list. This avoids the
* quadratic behavior that would result from shuffling a "sequential
* access" list in place.
*
* @param list the list to be shuffled.
* @param rnd the source of randomness to use to shuffle the list.
* @throws UnsupportedOperationException if the specified list or its
* list-iterator does not support the <tt>set</tt> operation.
*/
public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
} else {
Object arr[] = list.toArray(); // Shuffle array
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}

类Collections的shuffle()方法

由以上的jdk源码可见,在对实现list接口的对象进行洗牌,打乱时,区分了该类是否是RandomAccess的实例,这样做有什么意义呢?请继续向下看:

在jdk文档中对RandomAccess接口的定义如下:


/**
* Marker interface used by <tt>List</tt> 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.
*
* <p>The best algorithms for manipulating random access lists (such as
* <tt>ArrayList</tt>) can produce quadratic behavior when applied to
* sequential access lists (such as <tt>LinkedList</tt>). Generic list
* algorithms are encouraged to check whether the given list is an
* <tt>instanceof</tt> this interface before applying an algorithm that would
* provide poor performance if it were applied to a sequential access list,
* and to alter their behavior if necessary to guarantee acceptable
* performance.
*
* <p>It is recognized that the distinction between random and sequential
* access is often fuzzy. For example, some <tt>List</tt> implementations
* provide asymptotically linear access times if they get huge, but constant
* access times in practice. Such a <tt>List</tt> implementation
* should generally implement this interface. As a rule of thumb, a
* <tt>List</tt> implementation should implement this interface if,
* for typical instances of the class, this loop:
* <pre>
* for (int i=0, n=list.size(); i &lt; n; i++)
* list.get(i);
* </pre>
* runs faster than this loop:
* <pre>
* for (Iterator i=list.iterator(); i.hasNext(); )
* i.next();
* </pre>
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../guide/collections/index.html">
* Java Collections Framework</a>.
*
*/
public interface RandomAccess {
}

 

List 实现所使用的标记接口,用来表明其支持快速(通常是固定时间)随机访问。此接口的主要目的是允许一般的算法更改其行为,从而在将其应用到随机或连续访问列表时能提供良好的性能。

将操作随机访问列表的最佳算法(如 ArrayList )应用到连续访问列表(如 LinkedList )时,可产生二次项的行为。如果将某个算法应用到连续访问列表,那么在应用可能提供较差性能的算法前,鼓励使用一般的列表算法检查给定列表是否为此接口的一个 instanceof ,如果需要保证可接受的性能,还可以更改其行为。

现在已经认识到,随机和连续访问之间的区别通常是模糊的。例如,如果列表很大时,某些 List 实现提供渐进的线性访问时间,但实际上是固定的访问时间。这样的 List 实现通常应该实现此接口。

JDK中推荐的是对List集合尽量要实现RandomAccess接口

如果集合类是RandomAccess的实现,则尽量用for(int i = 0; i < size; i++) 来遍历而不要用Iterator迭代器来遍历,在效率上要差一些。反过来,如果List是Sequence List,则最好用迭代器来进行迭代。

JDK中说的很清楚,在对List特别是Huge size的List的遍历算法中,要尽量来判断是属于RandomAccess(如ArrayList)还是Sequence List (如LinkedList),因为适合RandomAccess List的遍历算法,用在Sequence List上就差别很大,常用的作法就是:
    要作一个判断:

if (list instance of RandomAccess) {
for(int m = 0; m < list.size(); m++){}
}else{
Iterator iter = list.iterator();
while(iter.hasNext()){}
}
 package testrandomaccess;  

 import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.RandomAccess; /**
*
* @author bolong
*/
public class TestRandomAccess {
// 初始化列表 public static void initList(List list, int n) {
for (int i = 0; i < n; i++) {
list.add(i);
}
}
//使用循环进行对列表的迭代 public static void traverseWithLoop(List list) {
long starttime = 0;
long endtime = 0;
starttime = System.currentTimeMillis();
for (int count = 0; count <= 1000; count++) {
for (int i = 0; i < list.size(); i++) {
list.get(i);
}
}
endtime = System.currentTimeMillis();
System.out.println("使用loop迭代一共花了" + (endtime - starttime) + "ms时间"); }
//使用迭代器对列表进行迭代 public static void traverseWithIterator(List list) {
long starttime = 0;
long endtime = 0;
starttime = System.currentTimeMillis();
for (int count = 0; count <= 1000; count++) {
for (Iterator itr = list.iterator(); itr.hasNext();) {
itr.next();
}
}
endtime = System.currentTimeMillis();
System.out.println("使用Iterator迭代一共花了" + (endtime - starttime) + "ms时间");
} public static void traverse(List list) { long starttime = 0;
long endtime = 0;
if (list instanceof RandomAccess) {
System.out.println("该list实现了RandomAccess接口");
starttime = System.currentTimeMillis();
for (int count = 0; count <= 1000; count++) {
for (int i = 0; i < list.size(); i++) {
list.get(i);
}
}
endtime = System.currentTimeMillis();
System.out.println("迭代一共花了" + (endtime - starttime) + "ms时间");
} else {
System.out.println("该list未实现RandomAccess接口");
starttime = System.currentTimeMillis();
for (int count = 0; count <= 1000; count++) {
for (Iterator itr = list.iterator(); itr.hasNext();) {
itr.next();
}
}
endtime = System.currentTimeMillis();
System.out.println("迭代一共花了" + (endtime - starttime) + "ms时间");
}
} public static void main(String[] args) {
ArrayList arraylist = new ArrayList();
LinkedList linkedlist = new LinkedList();
initList(arraylist, 1000);
initList(linkedlist, 1000);
traverse(arraylist);
traverse(linkedlist);
traverseWithIterator(arraylist);
traverseWithLoop(arraylist);
traverseWithIterator(linkedlist);
traverseWithLoop(linkedlist);
}
}

验证RandomAccess的代码

根据程序输出的结果的确证明了,arraylist等实现了RandomAccess接口的类在进行迭代时使用loop效率更高,而linkedList那些未实现该接口的类在进行迭代时使用Iterator进行迭代效率更高.

RandomAccess接口的使用的更多相关文章

  1. Java集合类:"随机访问" 的RandomAccess接口

    引出RandomAccess接口 如果我们用Java做开发的话,最常用的容器之一就是List集合了,而List集合中用的较多的就是ArrayList 和 LinkedList 两个类,这两者也常被用来 ...

  2. Java Collections Framework 之 RandomAccess接口

    在研究Collections类的排序算法时候,看到这样的代码 : public static <T> int binarySearch(List<? extends Comparab ...

  3. ArrayList集合实现RandomAccess接口有何作用?为何LinkedList集合却没实现这接口

    详见:https://blog.csdn.net/weixin_39148512/article/details/79234817 众所周知,在List集合中,我们经常会用到ArrayList以及Li ...

  4. 难倒你了吧!ArrayList 为啥要实现 RandomAccess 接口?

    作者:蔡先森_caiyq https://www.jianshu.com/p/3e2a9e4c9e01 在我们的开发中,List接口是最常见不过,而且我们几乎每天都在用ArrayList或者Linke ...

  5. randomAccess接口

    http://www.blogjava.net/lzqdiy/archive/2007/04/22/112578.html

  6. Java的四个标记接口:Serializable、Cloneable、RandomAccess和Remote接口

    一.概述 标记接口是一些没有属性和方法的接口,也是一种设计思想.Java中的一个标记接口表示的的是一种类的特性,实现了该标记接口的类则具有该特性.如实现了Serializable接口的类,表示这个类的 ...

  7. 关于接口 RandomAccess

    今天看到java.util.Collections这个工具类中的 public static <T> void fill(List<? super T> list, T obj ...

  8. 为什么这些java接口没有抽象方法?浅谈Java标记接口

    在jdk的源码中,存在这样的一些接口,他们不包含任何的(抽象)方法,但是却广泛的存在. 这种接口我们称之为Mark Interface,也就是标记接口. 这些接口呢,我们不用来实现任何的方法,他们的作 ...

  9. Java 之 List<T> 接口的实现:ArrayList

    Collection├List│├LinkedList│├ArrayList│└Vector│ └Stack└SetMap├Hashtable├HashMap└WeakHashMap ArrayLis ...

随机推荐

  1. [bzoj2843&&bzoj1180]极地旅行社 (lct)

    双倍经验双倍的幸福... 所以另一道是300大洋的世界T_T...虽然题目是一样的,不过2843数据范围小了一点... 都是lct基本操作 #include<cstdio> #includ ...

  2. TypeScript装饰器(decorators)

    装饰器是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上,可以修改类的行为. 装饰器使用 @expression这种形式,expression求值后必须为一个函数,它会在运行时被 ...

  3. Mybatis中是否需要依赖配置文件的名称要和mapper接口的名称一致 params错误

    一:当核心配置文件mapper标签下以resource形式指向依赖配置文件时,不需要 这样就可以加载到其相应的依赖配置文件通过namespace找到其相应的方法 二:如果mapper标签下以packa ...

  4. c++---天梯赛---查验身份证

    ★题目: ★题目分析:本题要求输入一个数字n,随后n行输入n个身份证号码.之后进行进一步的判断把错误的身份证号码输出.如果全部正确输出All passed. ★思路方法: ①按题目要求输入. ②对前1 ...

  5. Apache Commons介绍(转载)

    一.Commons BeanUtils说明:针对Bean的一个工具集.由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装. 二.Commons CLI说明:这 ...

  6. MyEclipse或Eclipse导出JavaDoc中文乱码问题解决

  7. Java数据持久层框架 MyBatis之API学习三(XML 映射配置文件)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  8. Django 类方式view进行进行用户验证

    问题: Django中,view的书写方式有两种,一种是def函数方式,一种是class方式,函数方式通过@login_required装饰器标记函数,就必须通过用户验证,而类,则没办法通过此方法进行 ...

  9. Git: 本地创建版本库用于多处同步

    问题背景 目前有一个 Android 和 一个 iOS 项目,两个项目底层使用相同的 C++ 代码.由于在开发迭代中代码时常更新,而且往往是今天 Android 部分修改一小部分,明天 iOS 部分修 ...

  10. eclipse中注释的代码依然会执行的解决方法

    问题: eclipse中注释的代码在debug的时候居然还能执行.那一刻内心是崩溃的.. 解决方案: 项目重编译显示都正常,并没有报错,然后发现项目编译后,WEB-INF/lib/classes中的c ...