import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;
public class MyArrayListIterator
{
public static void main( String args[] )
{
ArrayList <String> a =new ArrayList <String> ();
System.out.println( a.size() );
displayArrayList( a );
a.add( "hi");
System.out.println( a.size() );
displayArrayListDetail( a );
ArrayList <Contact> contactList = new ArrayList <Contact<();
Contact john = new Contact( "john" , "my address" );
Contact bobby = new Contact( "bobby" , "other address" );
contactList.add( john );
contactList.add( bobby );
Collections.sort( contactList , Contact.COMPARE_BY_ADDRESS );
} //end main
private static void displayArrayList( ArrayList a )
{
ListIterator it =a.listIterator() ; //ListIterator has prev and next , Iterator only goes forward
while ( it.hasNext () )
{
System.out.println( it.next() );
}
} //end displayArrayList()
private static void displayArrayListDetail( ArrayList a )
{
int counter = 0;
ListIterator it =a.listIterator() ;
while ( it.hasNext () )
{
System.out.println("Element [" + counter + "] = " + it.next() );
System.out.println(" -hasPrevious = " + it.hasPrevious( ) );
System.out.println(" -hasNext = " + it.hasNext());
System.out.println(" -previousIndex = " + it.previousIndex() ) ;
System.out.println(" -nextIndex = " + it.nextIndex()) ;
System.out.println();
counter++;
}
} // end displayArrayListDetail
} //end class
// Natural Ordering = http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
// define an external controllable ordering (which overrides the natural ordering)
public class Contact
{
private String name;
private String address;
Contact( String n , String a )
{
this.name = n;
this.address = a;
}
// INSIDE OF THE DATA OBJECT CLASS inner class?
protected static Comparator<StorageGateway> COMPARE_BY_ADDRESS = new Comparator<StorageGateway>()
{
public int compare( Contact first , Contact other )
{
return first.address.compareTo( other.address ); //this uses the Java Object Natural Ordering
}
};
} //end Contact class = data object