将list集合,元素随机打乱

 

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

    Collections.shuffle实现

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

     

posted @ 2018-10-19 11:35  _小豪豪  阅读(4195)  评论(0编辑  收藏  举报