Results 1 to 3 of 3
  1. #1
    lenny is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default How to use an Iterator in java

    Hi, My question is on how to use an Iterator in java. I understand that it is an interface with three methods, but someone said to me that Iterator is also a method in the Iterator class file. After defining the hasNext(), etc. methods, how would I use the iterator and define something of that type? I've tried to look up information on iterators, but I haven't found a good explanation of it anywhere.
    Using various user commands, we are to add words to the list (keeping the list in abc order), remove words from the list, print the current list, and check if a certain word is in the list. I have to use iterator in this program.

    Thanks.

  2. #2
    shanePreater is offline Member
    Join Date
    Jul 2007
    Location
    England, Bath
    Posts
    47
    Rep Power
    0

    Default

    I think you have slightly misunderstood the iterator method as this is not on the Iterator interface but is actually on the Collections which use the iterator.

    When obtaining an iterator from a Collection you would call the iterator() method which gives you an iterator of the correct type.

    In order to use your own iterator for your collection you would tend to implement the Collection interface (or simply extend an existing one) and then override the iterator method to return your custom version.

    You could then chuck your objects into your custom collection and acquire the iterator and voila.

    Hope this helps.

  3. #3
    Seemster is offline Member
    Join Date
    Jul 2007
    Posts
    55
    Rep Power
    0

    Default

    Here's a quick example:

    ArrayList<String> al = new ArrayList<String>();
    al.add("one");
    al.add("two");

    Iterator i = al.iterator();
    while (i.hasNext()) {
    String temp = (String) i.next();
    System.out.println(temp);
    }

    ============
    one
    two

    Note: I put a string into the array but you can put any object of any type and iterate through it.

Similar Threads

  1. Implementing Iterator
    By Harb in forum New To Java
    Replies: 13
    Last Post: 11-21-2009, 07:25 PM
  2. iterator issues
    By orchid in forum New To Java
    Replies: 2
    Last Post: 08-12-2008, 01:43 PM
  3. Iterator
    By eva in forum New To Java
    Replies: 0
    Last Post: 01-31-2008, 02:07 PM
  4. using Iterator with Vector
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-13-2007, 10:52 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •