这是我的代码:
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);
}
}
我知道如何改变List
,但如何使用Collections
来改组双端队列?
请回复代码,因为我还没有完全习惯Java术语/理论,我还在学习。
答案 0 :(得分:4)
您无法使用java.util.Collections
来移动Deque
;它仅适用于实现List
的集合。您可以编写自己的随机例程,也可以先创建List
,随机播放,然后将结果复制到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
接口不提供移动元素的方法。
答案 1 :(得分:1)
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);
}