将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);
    }

 

上一篇:【Azure 应用服务】App Service中抓取 Web Job 的 DUMP 办法


下一篇:python - 类属性