Home  >  Article  >  Java  >  Java Example - Collection Inversion

Java Example - Collection Inversion

黄舟
黄舟Original
2017-01-21 11:09:421403browse

The following examples demonstrate how to use the listIterator() and collection.reverse() methods of the Collection and Listiterator classes to reverse elements in a collection:

/*
 author by w3cschool.cc
 Main.java
 */

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("反转前");
      while (liter.hasNext())
         System.out.println(liter.next());
      Collections.reverse(l);
      liter = l.listIterator();
      System.out.println("反转后");
      while (liter.hasNext())
         System.out.println(liter.next());
   }
}

The output result of running the above code is:

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

The above is the Java example - the content of set reversal. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn