java rotate_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  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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值