Java uses ListIterator to reverse ArrayList

Source: Internet
Author: User

For the list,

Train of Thought Analysis: to traverse a list in reverse order, first obtain a ListIterator, use the for () hasNext () method as the judgment condition, and execute next () cyclically () the method locates the cursor at the end of the list, and then uses another hasPrevious () method as the judgment condition to output the elements in the list in reverse order using the previous () method.

The Code is 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 a list for (int I = 0; I <10; I ++) {// Add 10 elements to the list. add (I);} Iterator it = list. iterator (); System. out. print ("the element in the ArrayList set is:"); while (it. hasNext () {System. out. print (it. next () + "");} System. out. println (); System. out. println ("Backward:"); ListIterator <Integer> li = list. listIterator (); // obtain the ListIterator object for (li = list. listIterator (); li. hasNext ();) {// locate the cursor to the end of the list li. next () ;}for (; li. hasPrevious ();) {// The System element in the output list in reverse order. out. print (li. previous () + "");}}}

Effect

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.