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