title: Shuffling array of objects in Java: Why does this method work for int but not for my objects?
body: <p>I know, I know - there are hundreds of people on here asking how to shuffle and array 52 card objects in Java and I thought it would be simple enough. I've not used collections (based on advice on stack). I've tried the Fisher-Yates shuffle but I'm seeing what looks like really odd behaviour... Can anyone help?</p>
  
  <p>I based my solution on this answer: <a href="https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array">Random shuffling of an array</a></p>
  
  <p>And it works great... for numbers. This Class has two arrays, one containing the numbers from 0 to 51 and the other containing 52 Card objects with various instance variables like suit and number.</p>
  
  <p>This code works flawlessly:</p>
  
  <pre><code>public void shuffleNums()
     {
         Random rnd = new Random();
         for (int i = this.numbers.length -1; i &gt; 0; i--)
         {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            int temp = this.numbers[index];
            this.numbers[index] = this.numbers[i];
            this.numbers[i] = temp;
  
         }
     }
  </code></pre>
  
  <p>But when I try to use the same approach on a deck of 52 Card objects, like this:</p>
  
  <pre><code>public void shuffleCards()
     {
         Random rnd = new Random();
         for (int i = this.cards.length - 1; i &gt; 0; i--)
         {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            Card temp = this.cards[index];
            this.cards[index] = this.cards[i];
            this.cards[i] = temp;
  
         }
     }
  </code></pre>
  
  <p>It doesn't work so nice. Most of the cards are shuffled successfully but apparently I've dropped half the deck because now the array has about 16 NULL values and only about 36 random cards. The NULLs seem to be randomly distributed throughout the array.</p>
  
  <p>I could easily work around this but I want to understand why this is happening. Can anyone help me work out what's going on?</p>
  
  <p>EDIT:
  Regarding how I initialised the array - I had checked that the array did in fact have 52 Card objects listed from 2 of clubs up to Ace of spades. Before executing shuffle() the array correctly contained 52 card objects. Afterwards it contained roughly 36 - give or take.</p>