This commit is contained in:
parent
4d6526b3a4
commit
f474ff3ed6
1 changed files with 10 additions and 13 deletions
|
@ -1,7 +1,7 @@
|
||||||
package tech.sbdevelopment.themeparkaudio.api.maps;
|
package tech.sbdevelopment.themeparkaudio.api.maps;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Random;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link ArrayList} with shuffle support.
|
* An {@link ArrayList} with shuffle support.
|
||||||
|
@ -9,15 +9,14 @@ import java.util.Random;
|
||||||
* @param <E> The type you want to store
|
* @param <E> The type you want to store
|
||||||
*/
|
*/
|
||||||
public class SongList<E> extends ArrayList<E> {
|
public class SongList<E> extends ArrayList<E> {
|
||||||
private final Random r = new Random();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shuffle this List
|
* Shuffle this List using the Fisher-Yates algorithm
|
||||||
*/
|
*/
|
||||||
public void shuffle() {
|
public void shuffle() {
|
||||||
for (int index = 0; index < size(); index++) {
|
ThreadLocalRandom rnd = ThreadLocalRandom.current();
|
||||||
int secondIndex = r.nextInt(size());
|
for (int i = size() - 1; i > 0; i--) {
|
||||||
swap(index, secondIndex);
|
int index = rnd.nextInt(i + 1);
|
||||||
|
swap(index, i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -29,7 +28,7 @@ public class SongList<E> extends ArrayList<E> {
|
||||||
public E getRandom() {
|
public E getRandom() {
|
||||||
int size = size();
|
int size = size();
|
||||||
if (size == 0) return null;
|
if (size == 0) return null;
|
||||||
return get(r.nextInt(size()));
|
return get(ThreadLocalRandom.current().nextInt(size));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -39,10 +38,8 @@ public class SongList<E> extends ArrayList<E> {
|
||||||
* @param secondIndex The second index
|
* @param secondIndex The second index
|
||||||
*/
|
*/
|
||||||
private void swap(int firstIndex, int secondIndex) {
|
private void swap(int firstIndex, int secondIndex) {
|
||||||
E first = get(firstIndex);
|
E temp = get(firstIndex);
|
||||||
E second = get(secondIndex);
|
set(firstIndex, get(secondIndex));
|
||||||
|
set(secondIndex, temp);
|
||||||
set(secondIndex, first);
|
|
||||||
set(firstIndex, second);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
Loading…
Add table
Reference in a new issue