java打亂ArrayList產生一個隨機ArrayList列表,javaarraylist

來源:互聯網
上載者:User

java打亂ArrayList產生一個隨機ArrayList列表,javaarraylist

自己寫了一個,有時候會有需要。

public static <V> boolean isEmpty(ArrayList<V> sourceList) {        return (sourceList == null || sourceList.size() == 0);    }

/**     * 打亂ArrayList     *      * */    public static <V> ArrayList<V> randomList(ArrayList<V> sourceList){    if (isEmpty(sourceList)) {            return sourceList;        }        ArrayList<V> randomList = new ArrayList<V>( sourceList.size( ) );    do{    int randomIndex = Math.abs( new Random( ).nextInt( sourceList.size() ) );        randomList.add( sourceList.remove( randomIndex ) );    }while( sourceList.size( ) > 0 );        return randomList;    }



【java】助怎把一個數組元素隨機打亂順序,

暈.不用那麼麻煩.

先轉化為list(為什麼不一開始就用List呢?)

例:

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

直接調用shuffle,就是隨機排序

例:Collections.shuffle(list);

直接輸出就是你想要的結果
 
java怎打亂arraylist中的對象,一定不可以重複

只要隨即一個數,然後挑取出來插在最後,就不會有Bound的問題咯.
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.