1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/* Shuffle elements of Java ArrayList example This java example shows how to shuffle elements of Java ArrayList object using shuffle method of Collections class. */ import java.util.ArrayList; import java.util.Collections; public class ShuffleElementsOfArrayListExample { public static void main(String[] args) { //create an ArrayList object ArrayList arrayList = new ArrayList(); //Add elements to Arraylist arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); arrayList.add("D"); arrayList.add("E"); System.out.println("Before shuffling, ArrayList contains : " + arrayList); /* To shuffle elements of Java ArrayList use, static void shuffle(List list) method of Collections class. */ Collections.shuffle(arrayList); System.out.println("After shuffling, ArrayList contains : " + arrayList); } } /* Output would be Before shuffling, ArrayList contains : [A, B, C, D, E] After shuffling, ArrayList contains : [C, A, D, E, B] */ |
Excellent
An alternative implementation..
static <t> ArrayList<t> shuffleRight(ArrayList<t> list,int positions){
ArrayList<t> newList = new ArrayList<t>();
for (int i = 0; i < positions; i++) {
list.remove(list.size()-1);
}
for (int i = 0; i < positions; i++) {
newList.add(i, (T)new Integer(0));
}
for (int i = 0; i < list.size(); i++) {
newList.add(list.get(i));
}
return newList;
}
static <t> ArrayList<t> shuffleLeft(ArrayList<t> list,int positions){
ArrayList<t> newList = new ArrayList<t>();
for (int i = 0; i < positions;++i) {
list.remove(0);
}
for (int i = 0; i < list.size(); i++) {
newList.add(list.get(i));
}
for (int i = 0; i < positions; i++) {
newList.add((T)new Integer(0));
}
return newList;
}