java.util.Collections.reverse()方法是java.util.Collections类的方法。它颠倒了作为参数传递的列表中元素的顺序。
// Reverses elements of myList and returns Nothing. // For example, if list contains {1, 2, 3, 4}, it converts // list to {4, 3, 2, 1} public static void reverse(List myList) It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.
反转ArrayList或LinkedList。
// Java program to demonstrate working of java.utils.
// Collections.reverse()
import java.util.*;
public class ReverseDemo
{
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 reverse() method
// to reverse the element order of mylist
Collections.reverse(mylist);
System.out.println("Modified List: " + mylist);
}
}
输出:
Original List : [practice, code, quiz, geeksforgeeks] Modified List: [geeksforgeeks, quiz, code, practice]
对于Linkedlist,我们只需要用“ List”中的LinkedList替换ArrayList
Java中的Arrays类没有反向方法。我们可以使用Collections.reverse()来反转数组。
// Java program to demonstrate reversing of array
// with Collections.reverse()
import java.util.*;
public class ReverseDemo
{
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/
Collections.reverse(Arrays.asList(arr));
System.out.println("Modified Array : " +
Arrays.toString(arr));
}
}
输出:
Original Array : [10, 20, 30, 40, 50] Modified Array : [50, 40, 30, 20, 10]
相关用法
- Java Java lang.Long.lowestOneBit()用法及代码示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代码示例
- Java Java.util.Collections.rotate()用法及代码示例
- Java Java.util.concurrent.Phaser用法及代码示例
- Java Java.util.concurrent.RecursiveTask用法及代码示例
- Java Java.util.function.BiPredicate用法及代码示例
- Java Java lang.Long.reverse()用法及代码示例
- Java Java lang.Long.builtcount()用法及代码示例
- Java Java.util.function.IntPredicate用法及代码示例
- Java Java.util.function.DoublePredicate用法及代码示例
注:本文由纯净天空筛选整理自 Collections.reverse() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。