Arrays.sort not filling array, overwriting values that are already in the array
<p>I need to generate an array <code>int[] randomNumbers</code> of random numbers with no duplicates. To do this, I make an array with all values that can go into <code>randomNumbers</code>, then use a random number generator to pick one out of the list, check if it's already in <code>randomNumbers</code>, and if it isn't, put it in <code>randomNumbers</code>.</p>

<p>(I want numbers between 1 and max, not 0 and max-1)</p>

<p>To be able to use Arrays.sort(int[]), the list needs to be sorted. So I use a third array, with the same values as <code>randomNumbers</code> called <code>sortedNumbers</code>, and sort it on every iteration:</p>

<pre><code>public int[] uniqueRandom(int max, int numRequired) {
    if (max &lt; numRequired) {
        numRequired = max;
    }
    int[] randomNumbers = new int[numRequired];
    int[] sortedNumbers = new int[numRequired];
    int[] sequentialNumbers = new int[max];
    for (int i = 1; i &lt; max; i++) {
        sequentialNumbers[i] = i;
            System.out.println(sequentialNumbers[i]);
    }

    int p = 0;
    while (p &lt; numRequired) {
        int j = r.nextInt(max) + 1;
        System.out.println("J:" + j);
        if (Arrays.binarySearch(sortedNumbers, j) &gt;= 0) {
            System.out.println("Number Found:" + Arrays.binarySearch(randomNumbers,  j));
        } else {
            randomNumbers[p] = j;
            sortedNumbers[p] = j;
            Arrays.sort(sortedNumbers);
            for (int i = 0; i &lt; randomNumbers.length; i++) {
                System.out.println("rNum[" + i + "]:" + randomNumbers[i]);
            }
            System.out.println("\n");
            for (int i = 0; i &lt; randomNumbers.length; i++) {
                System.out.println("sNum[" + i + "]:" + sortedNumbers[i]);
            }
            p++;
        }

    }

    return randomNumbers;
}
</code></pre>

<p>My issue is that I'm getting an output where <code>sortedNumbers</code> is overwriting values. For uniqueRandom(5, 5) the output is:</p>

<pre><code>J:2
rNum[0]:2
rNum[1]:0
rNum[2]:0
rNum[3]:0
rNum[4]:0

sNum[0]:0
sNum[1]:0
sNum[2]:0
sNum[3]:0
sNum[4]:2


J:2 // 2 already in the list, try again


J:2


J:4
rNum[0]:2
rNum[1]:4
rNum[2]:0
rNum[3]:0
rNum[4]:0

sNum[0]:0
sNum[1]:0
sNum[2]:0
sNum[3]:2
sNum[4]:4


J:5
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:0
rNum[4]:0

sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:4
sNum[4]:5


J:2


J:3
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:3
rNum[4]:0

sNum[0]:0  // Should be:
sNum[1]:0  // 2
sNum[2]:2  // 3
sNum[3]:3  // 4
sNum[4]:5  // 5


J:4
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:3
rNum[4]:4

sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:3
sNum[4]:4
</code></pre>

<p>So you can see the issue. I'm using java 1.7, and have no idea why it's doing this!</p>
