Is the following program guaranteed to produce a list with the same contents and ordering in future java releases?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
Collections.shuffle(list, new Random(42));
}
}
The javadoc of the java.util.Random
class guarantees that it will always return the same random numbers if intialized with the same seed in all future java releases.
But are there any guarantees regarding the algorithm behind the java.util.Collections.shuffle()
utility function? The Javadoc for this utility function does not say anything about this.
I need this guarantee, because I want to be sure that persisted data will not be useless with any future java release.
The shuffle() is a Java Collections class method which works by randomly permuting the specified list elements. There is two different types of Java shuffle() method which can be differentiated depending on its parameter. These are: Java Collections shuffle(list) Method.
Set is unordered, so randomizing an unordered Collection doesn't make any logical sense. An ordered Set is ordered using a Comparator which means it has a fixed order, you can't shuffle it, that has no meaning as the order is determined by the Comparator or the compare() method.
The java. util. Collections class provides shuffle() method which can be used to randomize objects stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in a different order.
There is no explicit guarantee, as you say.
On the other hand, the existence of a separate Collections.shuffle(List,Random)
would suggest that the intention is that this method will always return the same order when invoked with a Random
in an identical state. (This is useful to create repeatable tests for example.)
So it's a bit of a grey area.
But if core functionality depends on it and you want to be absolutely sure, you can implement the Fisher-Yates algorithm (or rather, the more efficient Durstenfeld algorithm) yourself, it's simple. It's so simple that it's definitely not worth taking the (probably small) risk that Collections.shuffle()
will change in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With