Java Reverse Output list

Source: Internet
Author: User
Tags iterable

Post Code First

 Packagecom.tsubasa.collection;Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.Collection;ImportJava.util.Iterator; Public classReversiblearraylist<t>extendsArraylist<t>{     PublicReversiblearraylist (collection<t>c) {        Super(c); }     PublicIterable<t>reversed () {return NewIterable<t>() {@Override PublicIterator<t>iterator () {return NewIterator<t>(){                    intCurrent = Size ()-1 ; @Override Public BooleanHasnext () {returnCurrent >-1 ; } @Override PublicT Next () {returnGet (current--); } @Override Public voidRemove () {Throw Newunsupportedoperationexception ();            }                } ;    }                    } ; }         Public Static voidMain (string[] args) {reversiblearraylist<String> list =NewReversiblearraylist<string>(Arrays.aslist ("To being or not to being it is a question". Split (""))) ;  for(String str:list) {System.out.print (str+ " ");        } System.out.println ();  for(String str:list.reversed ()) {System.out.print (str+ " "); }    }}

Operation Result:

To being or not to being it is a question
Question A is it being to not or being to

The above solution uses the so-called adapter method , and the adapter part comes from design mode because we use foreach to iterate through the list, so we must provide an interface that satisfies foreach.

Since our ArrayList has implemented the Iterable interface, there are two options below to achieve reverse output:

1. Covering the original iterator method of ArrayList

2. You are producing a iterator interface.

Through the code above, it is obvious that we have chosen the second method here.

Java Reverse Output list

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.