Java Language Moving objects around in the list


Example

The Collections class allows for you to move objects around in the list using various methods (ls is the List):

Reversing a list:

Collections.reverse(ls);

Rotating positions of elements in a list

The rotate method requires an integer argument. This is how many spots to move it along the line by. An example of this is below:

List<String> ls = new ArrayList<String>();
ls.add(" how");
ls.add(" are");
ls.add(" you?");
ls.add("hello,");
Collections.rotate(ls, 1);

for(String line : ls) System.out.print(line);
System.out.println();

This will print "hello, how are you?"

Shuffling elements around in a list

Using the same list above, we can shuffle the elements in a list:

Collections.shuffle(ls);

We can also give it a java.util.Random object that it uses to randomly place objects in spots:

Random random = new Random(12); 
Collections.shuffle(ls, random);