Collection.shuffle not working - GWT

Using import java.util.Collections; as I should be. Not GWT. Ask for the error class in the shared folder for the GWT project.

The code has the following structure:

 List<String []> qaList; qaList = new ArrayList<String[]>(); qaList.add("12345 main st", "tomah"); qaList.add("124 main st", "lacrosse"); qaList.add("123 main", "yeeehahaaa"); Collections.shuffle(qaList); 

Gives me this error:

[ERROR] [_012cfaexam] - Line 109: The shuffle(List<String[]>) method shuffle(List<String[]>) is undefined for type collections

+6
source share
3 answers

Quote from the GWT JRE Emulation Reference :

The Google Web Toolkit includes a library that emulates a subset of the Java runtime library. The list below shows the set of packages, types, and JRE methods that GWT can automatically translate. Please note that in some cases only a subset of the methods for this type is supported.

In particular, if you look at Collections in the Package java.util , you will see that it does not contain the shuffle() method.

+7
source

There is another way to solve this error:

 Random random = new Random(qaList.size()); for(int index = 0; index < qaList.size(); index += 1) { Collections.swap(qaList, index, index + random.nextInt(qaList.size() - index)); } 
+4
source

In addition to what matsev already said:

If your code is GPL, you can simply copy the SUN implementation:

 public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); } else { Object arr[] = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list ListIterator it = list.listIterator(); for (int i=0; i<arr.length; i++) { it.next(); it.set(arr[i]); } } } 

Mostly Fisher Yates shuffle with some optimizations if the list is not random access.

+3
source

Source: https://habr.com/ru/post/912644/


All Articles