Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any guarantee that the algorithm behind java.util.Collections.shuffle() remains unchanged in future Java releases?

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.

like image 943
Daniel K. Avatar asked Jul 30 '15 09:07

Daniel K.


People also ask

Is shuffle method available in collection class?

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.

Can you shuffle a set in Java?

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.

Can you shuffle a list in Java?

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.


1 Answers

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.

like image 55
biziclop Avatar answered Oct 06 '22 01:10

biziclop