之前有谈过集合的随机返回,由于项目的需要必须要在集合的第一位体现出随机,所以我们采用了下面的方法:
public class FirstIndexRandom
{
public static void main(String[] args)
{
}
private static List<Integer> getNewOrderList(List<Integer> value)
{
Random rand = new Random();
int listIndex = rand.nextInt(value.size());
List<Integer> returnList = new ArrayList<Integer>();
returnList.add(value.get(listIndex));
value.remove(listIndex);
returnList.addAll(value);
return returnList;
}
}
随机选择集合中元素的一个下标,和第一位做交换,产生一次伪随机。
其实jdk中Collections(集合工具类)中,提供了对整个集合做一个随机返回的方法:
Collections.shuffle(list);
该方法能够打散集合中元素的顺序
下面我们看一下shuffle中的源码:
public static void shuffle(List list1)
{
Random random = r;
if(random == null)
r = random = new Random();
shuffle(list1, random);
}
public static void shuffle(List list1, Random random)
{
int i = list1.size();
if(i < 5 || (list1 instanceof RandomAccess))
{
for(int j = i; j > 1; j--)
swap(list1, j - 1, random.nextInt(j));
} else
{
Object aobj[] = list1.toArray();
for(int k = i; k > 1; k--)
swap(aobj, k - 1, random.nextInt(k));
ListIterator listiterator = list1.listIterator();
for(int l = 0; l < aobj.length; l++)
{
listiterator.next();
listiterator.set(aobj[l]);
}
}
}
在调用shuffle(List list)方法时,方法内部产生了一个随机数,接着调用下面的shuffle(list,random)方法。
这里实际上是运用了list中的set方法的特性,可以看一下jdk中的解释。
set方法可以替换指定下标元素,而本身会有一个返回值,就是被替换掉的元素。
详细的可以研究一下list中的set的方法。