Rotating Elements In a List using Collections.rotate Method

2 April 2007

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].

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

del.icio.us:Rotating Elements In a List  using Collections.rotate Method  digg:Rotating Elements In a List  using Collections.rotate Method  spurl:Rotating Elements In a List  using Collections.rotate Method  wists:Rotating Elements In a List  using Collections.rotate Method  simpy:Rotating Elements In a List  using Collections.rotate Method  newsvine:Rotating Elements In a List  using Collections.rotate Method  blinklist:Rotating Elements In a List  using Collections.rotate Method  furl:Rotating Elements In a List  using Collections.rotate Method  reddit:Rotating Elements In a List  using Collections.rotate Method  fark:Rotating Elements In a List  using Collections.rotate Method  blogmarks:Rotating Elements In a List  using Collections.rotate Method  Y!:Rotating Elements In a List  using Collections.rotate Method  smarking:Rotating Elements In a List  using Collections.rotate Method  magnolia:Rotating Elements In a List  using Collections.rotate Method  segnalo:Rotating Elements In a List  using Collections.rotate Method  gifttagging:Rotating Elements In a List  using Collections.rotate Method

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Rotating Elements In a List using Collections.rotate Method

Leave a Reply