Java Examples - Collection Reversal

Java 实例Java Examples

The following example demonstrates how to use the listIterator() method of the Collection and Listiterator classes and the collection.reverse() method to reverse the elements in a collection:

Main.java file

import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; class Main { public static void main(String[] args) { String[] coins = { "A", "B", "C", "D", "E" }; List l = new ArrayList(); for (int i = 0; i < coins.length; i++) l.add(coins[i]); ListIterator liter = l.listIterator(); System.out.println("Before reversal"); while (liter.hasNext()) System.out.println(liter.next()); Collections.reverse(l); liter = l.listIterator(); System.out.println("After reversal"); while (liter.hasNext()) System.out.println(liter.next()); } }

The output of running the above code is:

反转前
A
B
C
D
E
反转后
E
D
C
B
A

Java 实例Java Examples

Other Extensions