This is my code:
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);
}
}
I know how to shuffle a List
, but how do I use the Collections
to shuffle a deque? Please reply with code as I am not totally used to Java terms/theory, I am still learning.
You cannot use java.util.Collections
to shuffle a Deque
; it only works on collections that implement List
. You can write your own shuffle routine or you can first create a List
, shuffle it, and then copy the results to 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);
}
The problem with writing your own shuffle routine, of course, is that the Deque
interface does not provide a means of moving elements around.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments