Java Collections reverse()

reverse() 用于反转指定列表中元素的顺序。

1 语法

public static void reverse(List<?> list)  

2 参数

list:这是其元素要颠倒的列表。

3 返回值

4 Collections reverse()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.reverse的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create a list of strings
        List<String>  mylist = new ArrayList<String>();
        mylist.add("Java");
        mylist.add("PHP");
        mylist.add("Python");
        mylist.add("COBOL");
        System.out.println("Original List:- " + mylist);
        Collections.reverse(mylist);
        System.out.println("Modified List:- " + mylist);
    }
}

输出结果为:

Original List:- [Java, PHP, Python, COBOL]
Modified List:- [COBOL, Python, PHP, Java]

5 Collections reverse()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.reverse的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create a list of Integer
        List<Integer>  mylist = new ArrayList<Integer>();
        mylist.add(1);
        mylist.add(2);
        mylist.add(3);
        mylist.add(4);
        System.out.println("Original List:- " + mylist);
        Collections.reverse(mylist);
        System.out.println("Modified List:- " + mylist);
    }
}

输出结果为:

Original List:- [1, 2, 3, 4]
Modified List:- [4, 3, 2, 1]

6 Collections reverse()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.reverse的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create an array of integers
        Integer arr[] = {10, -20, 30, -40, 50};
        System.out.println("Original Array : " +Arrays.toString(arr));
        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]

 

热门文章

优秀文章