當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.util.Collections.rotate()用法及代碼示例


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<String>  mylist = new ArrayList<String>(); 
        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]


相關用法


注:本文由純淨天空篩選整理自 Java.util.Collections.rotate() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。