I think that the problem is not in the code you've provided. Try this (added logging and cards initialization) and it works:
private void tryToSuffle()
{
int newI;
Integer temp,temp2,temp3;
Random randIndex = new Random();
//initializing data.
Integer cardsInDeck = 52;
ArrayList<Integer> cards = new ArrayList<Integer>();
for (int i =0; i < cardsInDeck; i++) {
cards.add(i);
}
//....
//no change in the algorythm itself
for (int i = 0; i < cardsInDeck; i++) {
newI = randIndex.nextInt(cardsInDeck);
temp = cards.get(i);
temp2= cards.get(newI);
cards.set(i, temp2);
cards.set(newI, temp);
}
//printing the result.
for (int i =0; i < cardsInDeck; i++) {
System.out.println(cards.get(i));
}
}
So without changing the main algorythm it works as planned.
So probably what your not doing is assigning the returned value to the proper variable. Why inside this method your using some instance field cards
? Couldn't you pass them as argument?
EDIT:
Just to support what I've writen above I made this test, and it works (without changes in the shuffling algorythm):
public class ShufflerTest {
private final Integer cardsInDeck = 52;
public static void main(String args[])
{
new ShufflerTest().run();
}
private void run() {
ArrayList<Integer> cards = new ArrayList<Integer>();
for (int i =0; i < cardsInDeck; i++) {
cards.add(i);
}
cards = tryToShuffle(cards);
//printing the result.
System.out.println(cards.toString());
}
private ArrayList<Integer> tryToShuffle(final ArrayList<Integer> cards)
{
int newI;
Integer temp,temp2;
Random randIndex = new Random();
ArrayList<Integer> shuffledCards = new ArrayList<Integer>();
shuffledCards.addAll(cards);
for (int i = 0; i < cardsInDeck; i++) {
newI = randIndex.nextInt(cardsInDeck);
temp = shuffledCards.get(i);
temp2= shuffledCards.get(newI);
shuffledCards.set(i, temp2);
shuffledCards.set(newI, temp);
}
return shuffledCards;
}
}
In the example I've added the shuffledCards
array not to change the original cards
array. This is good practice not to mess with the input param collection as you don't know if some other class uses it also. But if you decide not too use this additional shuffledCards
variable it would work also.
My example output is (i've changed it to cards.toString() replacing the loop):
[46, 16, 23, 21, 28, 8, 37, 4, 47, 17, 9, 41, 51, 30, 20, 26, 10, 3, 2, 14, 29, 40, 25, 33, 34, 42, 15, 27, 32, 43, 39, 6, 22, 45, 31, 35, 48, 13, 5, 1, 12, 19, 49, 50, 44, 11, 7, 0, 18, 24, 38, 36]