View RSS Feed

My Java Tips

Rotating Elements In a List using Collections.rotate Method

Rate this Entry
by , 11-08-2011 at 06:22 PM (3111 Views)
Collections have very useful methods. Let us see how to rotate objects in a given list. The method "rotate" has two inputs, a list and a distance parameter which defines rotation distance. The distance can be positive, negative or zero. Objects in the list will be rotated by the specified parameter. Let us take an example to rotate objects of Car class.

For example, suppose list comprises [t, a, n, k, s]. After invoking



Collections.rotate(list, 1) (or Collections.rotate(list, -4)), list will comprise [s, t, a, n, k].

Java Code:
package test;

import java.util.ArrayList;

import java.util.Collections;import java.util.Iterator;

import java.util.List; public class ListExample {List list;

public ListExample() {

	list = new ArrayList();}

private List getList() {

	return list;}

public static void main(String[] args) {

	ListExample lExam = new ListExample();List tempList = lExam.getList();

	tempList.add(new Car(2));

	tempList.add(new Car(3));tempList.add(new Car(1));

	tempList.add(new Car(6));Collections.rotate(tempList,2);

	Iterator iterator = lExam.getList().iterator();

	while (iterator.hasNext()) {

		System.out.println(((Car)iterator.next()).getCapacity());

	}

}

}

package test;

class Car {

	int capacity;public Car(int c) {

		this.capacity = c;

	}public int getCapacity() {

		return capacity;

	}}
Output :

1

6

23

Submit "Rotating Elements In a List  using Collections.rotate Method" to Facebook Submit "Rotating Elements In a List  using Collections.rotate Method" to Digg Submit "Rotating Elements In a List  using Collections.rotate Method" to del.icio.us Submit "Rotating Elements In a List  using Collections.rotate Method" to StumbleUpon Submit "Rotating Elements In a List  using Collections.rotate Method" to Google

Comments