其他分享
首页 > 其他分享> > 将list集合,元素随机打乱

将list集合,元素随机打乱

作者:互联网

1:for循环+随机数 实现相同位置的元素交换

public <T> void shuffle(List<T> list) {
        int size = list.size();
        Random random = new Random();

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

            int randomPos = random.nextInt(size);

            T temp = list.get(i);
            list.set(i, list.get(randomPos));
            list.set(randomPos, temp);
        }
    }

2:Collections.swap实现

public <T> void shuffle(List<T> list) {
        int size = list.size();
        Random random = new Random();

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

            int randomPos = random.nextInt(size);

            Collections.swap(list, i, randomPos);
        }
    }

3:Collections.shuffle实现

 public <T> void shuffle(List<T> list){
        Collections.shuffle(list);
    }

 

标签:shuffle,int,打乱,random,list,随机,randomPos,size
来源: https://www.cnblogs.com/jelly12345/p/15908804.html