📜  Java Java () 方法与示例

📅  最后修改于: 2022-05-13 01:54:25.210000             🧑  作者: Mango

Java Java () 方法与示例

Java.util.Collections.rotate()方法存在于Java.util.Collections 类中。它用于将指定集合列表中存在的元素旋转给定距离。

Syntax:
public static void rotate(List< type > list, int distance)
Parameters : 
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.
Returns :
NA
Throws:
UnsupportedOperationException - if the specified list or 
its list-iterator does not support the set operation.

距离值没有限制。它可能为零、负数或大于 list.size()。调用此方法后,索引 i 处的元素将是先前位于索引 (i – 距离) mod list.size() 处的元素,对于 i 的所有值介于 0 和 list.size()-1 之间,包括 0 和 list.size()-1。

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

如何使用 rotate() 在Java中快速旋转数组?

Java中的数组类没有旋转方法。我们也可以使用 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]