This question has a follow-up: Follow up to Shuffling a list of track indices
I have a bunch of paths in an ArrayList<String>
and when a user has activated the shuffle button, I want to have a random order to play all of them. This class should help me get every index once. The methods getNext()
and getPrevious()
should help me to get the last / next song when the user clicks on either the next or previous button.
public class ShuffleGenerator {
private ArrayList<Integer> indexList;
private int currentIndex;
public ShuffleGenerator(){
indexList = new ArrayList<Integer>();
currentIndex = 0;
}
public void initalize( int seed, int size ){
if( !indexList.isEmpty() ){
indexList.clear();
}
if( size > 0 ){
//fill it with indices
ArrayList<Integer> indices = new ArrayList<Integer>();
for( int i = 0; i < size; i++ ){
indices.add(i);
}
Random rnd = new Random(seed);
do{
int index = rnd.nextInt(indices.size());
indexList.add( indices.get(index) );
indices.remove(index);
}while( indices.size() > 0 );
}
}
/**
* Get the next index.
* @return -1 if failed otherweise the index.
*/
public int getNext(){
//if currentIndex is invalid
if( currentIndex+1 >= indexList.size() || indexList.isEmpty() ){
return -1;
}
currentIndex++;
return indexList.get(currentIndex);
}
/**
* Get the previous index.
* @return -1 if failed otherwise the index.
*/
public int getPrevious(){
//if currentIndex is invalid
if( currentIndex-1 < 0 || indexList.isEmpty() ){
return -1;
}
//decrement the current index so we can get the previous one
currentIndex--;
return indexList.get(currentIndex);
}
}
I tested it twice and it seems like I get every index from 0 to size-1
in a random order. But is it really giving me every index? I might have made a mistake and just not noticed yet. And is there anything to improve?