java 把一个List数组随机打乱顺序

方法一:推荐

直接调用Collections.shuffle(list),这个是系统方法,比较简单实用

String[] arr = new String[] {"1", "2"};
List list = Arrays.asList(arr);

直接调用shuffle,就是随机排序 

Collections.shuffle(list);

方法二:

算法:顺序遍历,每次生成一个随机位置,和当前位置的元素互换。

    public static ArrayList randomList(ArrayList sourceList) {
        if (sourceList == null || sourceList.size() == 0) {
            return sourceList;
        }
        ArrayList randomList = new ArrayList(sourceList.size());
        do {
            int randomIndex = Math.abs(new Random().nextInt(sourceList.size()));
            randomList.add(sourceList.remove(randomIndex));
        } while (sourceList.size() > 0);
        return randomList;
    }

附带数组操作方法

    /**
     * 对给定数目的自0开始步长为1的数字序列进行乱序
     *
     * @param no 给定数目
     * @return 乱序后的数组
     */
    public static int[] getSequence(int no) {
        int[] sequence = new int[no];
        for (int i = 0; i < no; i++) {
            sequence[i] = i;
        }
        Random random = new Random();
        for (int i = 0; i < no; i++) {
            int p = random.nextInt(no);
            int tmp = sequence[i];
            sequence[i] = sequence[p];
            sequence[p] = tmp;
        }
        random = null;
        return sequence;
    }

 

你可能感兴趣的:(java)