Question

The more specific question is, I want to be able to shuffle an array, whether it contains integers, strings, objects or something else. Using Comparable type seems to be problematic, and I don't want to use int[] or String[] because I want to use a more general class that allows arrays of all of these types to be shuffled using the same Shuffle class.

Here's my code.

import java.lang.Math;

public class Shuffle
{
    public Shuffle() {}

    public void shuffle(Comparable[] a)
    {
        int n= a.length;
        int j;
        for (int i=1; i<n; i++)
        {
            j= (int)(Math.random()*(i+1));
            if (i!=j) swap(a, i, j);
        }
    }

    protected void swap(Comparable[] a, int i, int j)
    {
        Comparable temp= a[i];
        a[i]= a[j];
        a[j]= temp;
    }

}
Was it helpful?

Solution

Your shuffle and swap methods aren't using compareTo, so there is no reason to make the type Comparable.

In this case, an Object[] seems to be the best option, as a replacement for Comparable[]. Any objects can be shuffled. That's as general as it gets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top