Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between iterators in Java and C++?

Tags:

java

c++

iterator

How is the implementation of Iterator in Java different from that in C++?

like image 769
ria Avatar asked Dec 03 '22 15:12

ria


1 Answers

In the current C++ (98) standard library (in particular the portion formerly known as STL) defines a form of iterators that are very close to C pointers (including arithmetic). As such they just point somewhere. To be useful, you generally need two pointers so that you can iterate between them. I understand C++0x introduces ranges which act more like Java iterators.

Java introduced the Iterator (and ListIterator) interface in 1.2, largely taking over from the more verbose Enumerable. Java has no pointer arithmetic, so there is no need to behave like a pointer. They have a hasNext method to see if they have go to the end, instead of requiring two iterators. The downside is that they are less flexible. The system requires methods as subList rather than iterating between two iterators are specific points in the containing list.

A general difference in style is that whereas C++ use "static polymorphism" through templates, Java uses interfaces and the common dynamic polymorphism.

The concept of iterators is to provide the glue to allow separation of "algorithm" (really control flow) and data container. Both approaches do that reasonably well. In ideal situations "normal" code should barely see iterators.

like image 130
Tom Hawtin - tackline Avatar answered Dec 09 '22 14:12

Tom Hawtin - tackline