Why is Java’s Iterator not an Iterable?

An iterator is stateful. The idea is that if you call Iterable.iterator() twice you’ll get independent iterators – for most iterables, anyway. That clearly wouldn’t be the case in your scenario. For example, I can usually write: public void iterateOver(Iterable<String> strings) { for (String x : strings) { System.out.println(x); } for (String x : strings) … Read more

Why are Standard iterator ranges [begin, end) instead of [begin, end]?

The best argument easily is the one made by Dijkstra himself: You want the size of the range to be a simple difference end − begin; including the lower bound is more “natural” when sequences degenerate to empty ones, and also because the alternative (excluding the lower bound) would require the existence of a “one-before-the-beginning” sentinel value. … Read more

What is the reason behind cbegin/cend?

It’s quite simple. Say I have a vector: std::vector<int> vec; I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to std::for_each: std::for_each(vec.begin(), vec.end(), SomeFunctor()); In C++03, SomeFunctor was free to be able to modify the parameter it gets. Sure, SomeFunctor could take its parameter … Read more

has_next in Python iterators?

There’s an alternative to the StopIteration by using next(iterator, default_value). For exapmle: >>> a = iter(‘hi’) >>> print next(a, None) h >>> print next(a, None) i >>> print next(a, None) None So you can detect for None or other pre-specified value for end of the iterator if you don’t want the exception way.

How to get a reversed list view on a list in Java?

Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won’t have to copy the list. Then just use Collections. Ergo, Collections.reverse(list.clone()); If you are using a List and don’t have access to clone() you can use subList(): List<?> shallowCopy … Read more