集册 Java实例教程 随机排列ArrayList中的所有条目

随机排列ArrayList中的所有条目

欢马劈雪     最近更新时间:2020-01-02 10:19:05

535
随机排列ArrayList中的所有条目
/* from 
nowjava.com - 时  代  Java*/


//package com.nowjava;

import java.util.ArrayList;


public class Main {

    /** 

     * randomly permutes all entries in an ArrayList

     * 

     * @param arrayList the ArrayList that you want to shuffle

     */

    public static <T extends Comparable<? super T>> void shuffle(

            ArrayList<T> arrayList) {

        for (int i = 0; i < arrayList.size(); i++) {

            swap(arrayList, i, (int) (Math.random() * arrayList.size()));

        }

    }


    /**

     * swaps two entries of an ArrayList

     * 

     * @param arrayList  the ArrayList whose entries you want to swap

     * @param yin  the index of the first swapped entry

     * @param yang  the index of the other swapped entry

     */

    public static <T extends Comparable<? super T>> void swap(

            ArrayList<T> arrayList, 
展开阅读全文