Performance of traditional for loop vs Iterator/foreach in Java

Assuming this is what you meant: // traditional for loop for (int i = 0; i < collection.size(); i++) { T obj = collection.get(i); // snip } // using iterator Iterator<T> iter = collection.iterator(); while (iter.hasNext()) { T obj = iter.next(); // snip } // using iterator internally (confirm it yourself using javap -c) for … Read more

Iterable objects and array type hinting?

I think you mean instanceof Iterator, PHP doesn’t have an Iterable interface. It does have a Traversable interface though. Iterator and IteratorAggregate both extend Traversable (and AFAIK they are the only ones to do so). But no, objects implementing Traversable won’t pass the is_array() check, nor there is a built-in is_iterable() function. A check you … Read more

how portable is end iterator decrement?

I think this is the relevant clause: ISO/IEC 14882:2003 C++ Standard 23.1.1/12 – Sequences Table 68 lists sequence operations that are provided for some types of sequential containers but not others. An implementation shall provide these operations for all container types shown in the “container” column, and shall implement them so as to take amortized … Read more

Why is “!=” used with iterators instead of “

All iterators are equality comparable. Only random access iterators are relationally comparable. Input iterators, forward iterators, and bidirectional iterators are not relationally comparable. Thus, the comparison using != is more generic and flexible than the comparison using <. There are different categories of iterators because not all ranges of elements have the same access properties. … Read more

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the “last” element. If you want something that’s ordered, you can use a SortedSet/NavigableSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1); If you really need the last element you should … Read more

What’s faster, iterating an STL vector with vector::iterator or with at()?

Using an iterator results in incrementing a pointer (for incrementing) and for dereferencing into dereferencing a pointer. With an index, incrementing should be equally fast, but looking up an element involves an addition (data pointer+index) and dereferencing that pointer, but the difference should be marginal. at() also checks if the index is within the bounds, … Read more

Python class accessible by iterator and index

The current accepted answer from @Ignacio Vazquez-Abrams is sufficient. However, others interested in this question may want to consider inheriting their class from an abstract base class (ABC) (such as those found in the standard module collections.abc). This does a number of things (there are probably others as well): ensures that all of the methods … Read more