【问题标题】:Collection.shuffle not working - GWTCollection.shuffle 不工作 - GWT
【发布时间】:2012-04-07 07:40:01
【问题描述】:

像我应该的那样使用import java.util.Collections;。不是 GWT 的。在 GWT 项目的共享文件夹中保存有错误的类。

代码是这样的结构:

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);

给我这个错误:

[ERROR] [_012cfaexam] - 第 109 行:方法 shuffle(List&lt;String[]&gt;) 未定义 >type Collections

【问题讨论】:

    标签: java collections shuffle


    【解决方案1】:

    引用自GWT's JRE Emulation Reference

    Google Web Toolkit 包含一个模拟 Java 运行时库子集的库。下面的列表显示了 GWT 可以自动翻译的一组 JRE 包、类型和方法。请注意,在某些情况下,给定类型仅支持方法的子集。

    具体来说,如果您查看Package java.util 中的Collections,您会发现它不包含shuffle() 方法。

    【讨论】:

    • 我有点困惑,因为我不是从“内部”GWT 调用它。我将它放在 appengine 上 GWT 项目的共享文件夹中。我以为这个文件夹是在服务器上执行的。一定不是。无论如何,谢谢,我将不得不阅读更多内容,并可能将其放在服务器文件夹中并进行异步调用以获取数据。
    • @user1318747 可以在客户端和服务器上调用“共享”包。 'server' 包仅适用于服务器。
    【解决方案2】:

    还有另一种方法可以解决这个错误:

    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));  
    }
    

    【讨论】:

      【解决方案3】:

      除了matsev已经说过的:

      如果你的代码是 GPL,你可以复制 SUN 的实现:

      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]);
              }
          }
      }
      

      它基本上是Fisher Yates shuffle,并进行了一些优化,以防列表不是随机访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多