mercredi 27 mai 2015

Non-Repeating Random Number Generator in Java

I am trying to create a subclass of the Random class in Java that does not repeat its output, and here is what I've got so far ..

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

public class NonRepetitiveRandom extends java.util.Random {
    private Set<Integer> noUseInts = new CopyOnWriteArraySet<Integer>();
    private static final long serialVersionUID = 1L;

    @Override
    protected int next(int bits) {
        int i;
        for (i = super.next(bits); noUseInts.contains(i); i = super.next(bits))
            ;
        noUseInts.add(i);
        return i;
    }
}

Is it fine ? Do I need to add anything ? I initially tried overriding each next* method using the same model as above, but after noticing that the next method itself is used in all next* methods, I am trying to override it alone.




Aucun commentaire:

Enregistrer un commentaire