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