java 编写shuffle方法_在java中为播放列表创建一个shuffle方法

该程序崩溃,这是因为,在 shuffle 方法中, while (songs.size()>0){ 始终为 true . The size of list is not changed.

如果你想用自己的方法编写 shuffle 方法,那么一个简单的方法是 iterater the songs list 和 swap 2 songs of current index i and the song with a random index .

public void shuffle (List songsList)

{

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

{

//Do something here

//generate a random number

//Swap songs according to the i index and and random index.

}

}

最简单的方法是使用 Collections # shuffle 方法使列表随机 .

Collections中相应的shuffle源代码如下:

/**

* Randomly permutes the specified list using a default source of

* randomness. All permutations occur with approximately equal

* likelihood.

*

* The hedge "approximately" is used in the foregoing description because

* default source of randomness is only approximately an unbiased source

* of independently chosen bits. If it were a perfect source of randomly

* chosen bits, then the algorithm would choose permutations with perfect

* uniformity.

*

* This implementation traverses the list backwards, from the last element

* up to the second, repeatedly swapping a randomly selected element into

* the "current position". Elements are randomly selected from the

* portion of the list that runs from the first element to the current

* position, inclusive.

*

* This method runs in linear time. If the specified list does not

* implement the {@link RandomAccess} interface and is large, this

* implementation dumps the specified list into an array before shuffling

* it, and dumps the shuffled array back into the list. This avoids the

* quadratic behavior that would result from shuffling a "sequential

* access" list in place.

*

* @param list the list to be shuffled.

* @throws UnsupportedOperationException if the specified list or

* its list-iterator does not support the set method.

*/

public static void shuffle(List> list) {

shuffle(list, r);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值