最近开发中,需要随机从好友列表取出指定数字的好友,然后推荐给用户关注,在网上找到了类似的算法,给大家分享下:package com.zuidaima.util.random;
import java.util.Random;
public class TestRandomArray {
public static void main(String[] args) {
String[] ids = new String[] { "zuidaima.com", "javaniu.com",
"zuidaima", "最代码", "java牛", "netbeans", "eclipse", "jsp",
"jstl", "javaniu", "jgroups", "java", "spring", "freemarker",
"hibernate", "struts" };
Random r = new Random();
String strarray[] = new String[5];
int index = 0;
for (int i = 0; i < 5; i++) {
// 刚开始从数组中随机抽取一个
// 而后将抽取的元素后面的元素向前推进到随机的位置[index位置]
// 随着循环的继续,逐渐抛弃后面的元素
index = r.nextInt(ids.length - i);
strarray[i] = ids[index];
// 元素向前推进到随机[index]的位置
for (int j = index; j < ids.length - i - 1; j++) {
ids[j] = ids[j + 1];
}
}
for (String str : strarray) {
System.out.print(str + " ");
}
}
}
运行如下图:

第二种算法:public static void r2() {
List ids = new ArrayList();
ids.add("zuidaima.com");
ids.add("zuidaima");
ids.add("最代码");
ids.add("javaniu");
ids.add("javaniu.com");
ids.add("www.zuidaima.com");
Random r = new Random();
List ret = new ArrayList();
int index = 0;
for (int i = 0; i < 3; i++) {
index = r.nextInt(ids.size() - i);
ret.add(ids.get(index));
ids.remove(index);
}
for (String str : ret) {
System.out.print(str + " ");
}
}
借助java的list数据结构来实现!