I have created a method to randomize the list:
public <T> List<T> randomize(List<T> list) {
LinkedList<T> randomizedList = new LinkedList<>();
Random random = new Random(list.size());
for (int i = random.nextInt(); i < list.size(); i++) {
randomizedList.add(list.get(i));
}
return randomizedList;
}
The list that I am passing to this method contains for e.g. five elements. When I am creating Random random = new Random(list.size()); I expect so when I call random.nextInt() what it will return me the random integer which will be an index of the list element.
But when I call random.nextInt(); instead of returning the number from the interval [0, 4] (which I expect to be returned) it returns me the value of for e.g.: -349120689. Which gives me an java.lang.IndexOutOfBoundsException: Index: -349120689, Size: 5.
Why is this happening and how to solve this?
new Random(list.size());this sets the seed of the Random number generator tolist.size();I suggest changing tonew Random()(which will give you a seed based on the current time of the system). Preferably though, you’d want to reuse the same Random object at all times.random.nextInt();here is where you’d want to putrandom.nextInt(list.size());which will give you a number from 0 to list.size() – 1.Even with the above changes, your code would just give you a sublist of the list starting at a random index and going until the end. Use
Collections.shuffle(list)instead.To do a real shuffling, you would need to “remember” which elements
you have inserted or not. In pseudo-code, you could do the
following: