将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); }
郭慕荣博客园