Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use Iterators

Collection Classes

How to use Iterators

by  FredrikN  Posted    (Edited  )
This is an simple example how you can use an Iterator with an Array

import java.util.*;


public class Driver
{

public static void main(String[] in)
{

MinArray arr = new MinArray();

arr.add("String1");
arr.add("String2");
arr.add("String3");


while(arr.hasNext())
{
System.out.print(arr.next());
}

System.out.println();

}


}


---------------------------------------------------

import java.util.*;

public class MinArray implements Iterator
{

private Vector v;
private int index = 0;

MinArray()
{

v = new Vector();

}

public void add(String in)
{
v.add(in);
}


public boolean hasNext()
{
return (index < v.size());
}


public Object next()
{
return v.get(index++);
}


public void remove()
{
throw new UnsupportedOperationException("Error");
}




}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top