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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What's the right way to use iterators? 1

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
0
0
US
Hi, I'm a C++ guy, and using iterators in C++ is simple.
Unfortunately, they work a lot differently in Java. :-(
In C++, I'd do something like this:
Code:
vector<string> strings;
...
for ( iterator<string> it = strings.begin(); it != strings.end(); ++it )
{
   cout << *it << endl;  // Print each string on a new line.
}
I tried doing this in Java:
Code:
Vector<String> strings;
...
iterator<String> it = Vector.iterator();
for ( String str = it.next(); it.hasNext(); str = it.next() )
{
   System.out.println( str );
}
But, it never prints the last index of the vector since the hasNext() returns false before the last string is pulled out of the iterator.

What's the Java equivalent of what I'd normally do in C++?
 
Code:
Vector<String> strings;
...
for (String str : strings)
{
        System.out.println (str);
}
Read : as 'in'.
If you insist on an iterator:
Code:
		Vector <String> strings = new Vector <String> ();
		strings.add ("Foo");
		strings.add ("Bar");
		strings.add ("Foobar");
		
		Iterator <String> it = strings.iterator ();
		while (it.hasNext())
		{
			String str = it.next(); 
			System.out.println (str);
		}
Note: it is Iterator, not iterator, and strings.iterator (), not Vector.iterator.

Note: If you don't have a strong reason to use Vector, the usage of ArrayList is recommended.
Code:
		List <String> strings = new ArrayList <String> ();
		strings.add ("Foo");
		strings.add ("Bar");
		strings.add ("Foobar");
		for (String str : strings)
		{
		        System.out.println (str);
		}

seeking a job as java-programmer in Berlin:
 
Oops, I missed those typos.

Why is ArrayList better than a Vector?

If they're similar to their C++ counterparts, a vector is contiguous in memory like an array, and a list is a linked-list of elements.

A vector is usually preferred in C++ unless you plan on adding or deleting elements from the middle of the sequence.
 
Vector contains code to make it synchronized, which affects its performance, whithout really reaching threadsafety.

For ArrayList you get indexed access like in Vector too.
Look at the javadocs for the public methods.
In the src.zip you may check the implementation.

seeking a job as java-programmer in Berlin:
 
OK thanks. I'll try that weird for (String str : strings) syntax...
I think I also saw something like that in a VBScript book (or maybe it was C#).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top