/*** Book: Thinking in Java * Features: We want to add the ability to generate a reverse iterator based on the default forward iterator. * File: adaptermethodidiom.java* time: April 8, 2015 19:59:01* Author: cutter_point*/package Lesson11holdingyourobjects;import Java.util.*;class reversiblearraylist<t> extends Arraylist<t>{public reversiblearraylist (Collection <T> c) {super (c);} Public iterable<t> reversed () {return new iterable<t> ()//first anonymous inner class {@Overridepublic iterator<t> Iterator ()//iterable must implement method {return new iterator<t> ()//return value is the second anonymous inner class {int current = size ()-1;// This size is the function inside the ArrayList, inheriting the @overridepublic Boolean Hasnext () {return current >-1;} @Overridepublic T Next () {return get (current--);//This is forward} @Overridepublic void Remove () {throw new Unsupportedoperationexception ();}};}};}} public class Adaptermethodidiom {public static void main (String [] args) {reversiblearraylist<string> ral = new Rever Siblearraylist<string> (Arrays.aslist ("To is or not to is". Split ("))); for (String s:ral) System.out.print (S +" "); SystEm.out.println ();//forward traversal for (String s:ral.reversed ()) System.out.print (S + "");}}
Preview:
To is or not to IS
Be-to-not or is to
"Thinkinginjava" 23, Reverse iterator