java.util.Collections类中提供了java.util.Collections.rotate()方法。它用于将存在于指定Collection列表中的元素旋转给定距离。
用法:
public static void rotate(List< type > list, int distance)
参数:
list - the list to be rotated.
distance - the distance to rotate the list.
type - Type of list to be rotated. Examples of
types are Integer, String, etc.
返回:
NA
Throws:
UnsupportedOperationException - if the specified list or
its list-iterator does not support the set operation.
距离值没有限制。它可以是零,负数或大于list.size()。调用此方法后,对于i介于0和list.size()-1(包括两端)之间的所有值,索引i处的元素将是索引(i-距离)mod list.size()处的先前元素。
// Java program to demonstrate working of
// java.utils.Collections.rotate()
import java.util.*;
public class RotateDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List mylist = new ArrayList();
mylist.add("practice");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
System.out.println("Original List:" + mylist);
// Here we are using rotate() method
// to rotate the element by distance 2
Collections.rotate(mylist, 2);
System.out.println("Rotated List:" + mylist);
}
}
输出:
Original List:[practice, code, quiz, geeksforgeeks]
Rotated List:[quiz, geeksforgeeks, practice, code]
How to quickly rotate an array in Java using rotate()?
Java中的Arrays类没有Rotate方法。我们可以使用Collections.rotate()来快速旋转数组。
// Java program to demonstrate rotation of array
// with Collections.rotate()
import java.util.*;
public class RotateDemo
{
public static void main(String[] args)
{
// Let us create an array of integers
Integer arr[] = {10, 20, 30, 40, 50};
System.out.println("Original Array:" +
Arrays.toString(arr));
// Please refer below post for details of asList()
// https://www.geeksforgeeks.org/array-class-in-java/
// rotating an array by distance 2
Collections.rotate(Arrays.asList(arr), 2);
System.out.println("Modified Array:" +
Arrays.toString(arr));
}
}
输出:
Original Array:[10, 20, 30, 40, 50]
Modified Array:[40, 50, 10, 20, 30]