Java Language Lists Moving objects around in the list


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

Reversing a list:


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?");
Collections.rotate(ls, 1);

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

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:


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);