Results 1 to 3 of 3
Thread: How to use an Iterator in java
- 07-24-2007, 04:31 AM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
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.
- 07-24-2007, 12:03 PM #2
Member
- Join Date
- Jul 2007
- Location
- England, Bath
- Posts
- 47
- Rep Power
- 0
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.
- 07-25-2007, 07:46 PM #3
Member
- Join Date
- Jul 2007
- Posts
- 55
- Rep Power
- 0
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
-
Implementing Iterator
By Harb in forum New To JavaReplies: 13Last Post: 11-21-2009, 07:25 PM -
iterator issues
By orchid in forum New To JavaReplies: 2Last Post: 08-12-2008, 01:43 PM -
Iterator
By eva in forum New To JavaReplies: 0Last Post: 01-31-2008, 02:07 PM -
using Iterator with Vector
By Java Tip in forum Java TipReplies: 0Last Post: 11-13-2007, 10:52 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks