Java uses Listiterator reverse ArrayList sample sharing _java

Source: Internet
Author: User

Analysis: In order to traverse a list in reverse order, first of all to get a Listiterator object, using the for () loop, the Listiterator class Hasnext () method as a judgment condition, through the loop to execute the Listiterator class next () method to position the cursor at the end of the list, and then in another for loop, the Hasprevious () method of the Listiterator class is used as the criterion for determining the elements in the list in reverse order by the previous () method of the Listiterator class.

The code is as follows:

Copy Code code as follows:

Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.ListIterator;

public class Iteratordemo {
public static void Main (string[] args) {
list<integer> list = new arraylist<integer> ();//Create lists
for (int i = 0; i < i++) {//Add 10 elements to the list
List.add (i);
}
Iterator it = List.iterator ();
System.out.print ("Elements in the ArrayList collection are:");
while (It.hasnext ()) {
System.out.print (It.next () + "");
}
System.out.println ();
SYSTEM.OUT.PRINTLN ("After reverse order:");
Listiterator<integer> li = List.listiterator ();//Get Listiterator Object
for (Li = List.listiterator (); Li.hasnext ();) {//Position the cursor at the end of the list
Li.next ();
}
for (; Li.hasprevious ();) {//reverse-order output list elements
System.out.print (li.previous () + "");
}
}
}

Effect as shown:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.