2

这是我的代码:

import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.List;

public class ArrayDequeDemo {
   public static void main(String[] args) {

      // create an empty array deque with an initial capacity
      Deque<Integer> deque = new ArrayDeque<Integer>(8);

      // use add() method to add elements in the deque
      deque.add(15);
      deque.add(30);
      deque.add(20);
      deque.add(18);        

      // let us print all the elements available in deque
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }

      //Collections.shuffle((List<?>) deque);
      // getFirst() will retrieve element at first(head) position
      int retval = deque.getFirst();
      System.out.println("Retrieved Element is = " + retval);
   }
}

我知道如何洗牌 a List,但我如何使用Collections洗牌双端队列?请用代码回复,因为我不完全习惯 Java 术语/理论,我还在学习。

4

2 回答 2

4

你不能java.util.Collections用来洗牌Deque; 它仅适用于实现List. 您可以编写自己的 shuffle 例程,也可以先创建 a List,对其进行随机播放,然后将结果复制到 a Deque

public static void main(String[] args) {

  // create an empty array deque with an initial capacity
  List<Integer> list = new ArrayList<Integer>(8);

  // use add() method to add elements in the deque
  list.add(15);
  list.add(30);
  list.add(20);
  list.add(18);        

  // let us print all the elements available in deque
  for (Integer number : list) {
     System.out.println("Number = " + number);
  }

  Collections.shuffle(list);
  Deque<Integer> deque = new ArrayDeque<Integer>(list);
  // getFirst() will retrieve element at first(head) position
  int retval = deque.getFirst();
  System.out.println("Retrieved Element is = " + retval);
}

当然,编写自己的 shuffle 例程的问题在于Deque界面不提供移动元素的方法。

于 2013-10-08T21:28:02.933 回答
2

Collections.shuffle(List) 只接受 List 所以为了洗牌 Deque 你需要使用 Deque 的 LinkedList 实现。LinkedList 实现了 Deque 和 List 接口。请参阅http://docs.oracle.com/javase/tutorial/collections/implementations/deque.html

public static void main(String[] args) {

    LinkedList<Integer> list = new LinkedList<Integer>();

    // use add() method to add elements in the deque
    list.add(15);
    list.add(30);
    list.add(20);
    list.add(18);

    // let us print all the elements available in deque
    for (Integer number : list) {
        System.out.println("Number = " + number);
    }

    Collections.shuffle(list);
    int retval = list.getFirst();
    System.out.println("Retrieved Element is = " + retval);
}
于 2013-10-08T21:49:36.627 回答