Re: Generics - Is this possible?
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Patricia Shanahan schreef:
| Logan Shaw wrote:
| ...
|> Is there a reason why an enhanced for loop couldn't be built to use
|> either
|> an Iterator or an Iterable?
|>
|> There are cases when we have a priori that an Iterator object exists.
|> For example, some API returns an Iterator. (There are other legit uses.)
|> In those cases, it would nice to be able to use the object at hand.
| ...
|
| Here's a solution that I just worked out for my own use:
|
| import java.util.Iterator;
|
| /**
| * Iterable whose iterator() method returns a
| * specified Iterator.
| * @param <T> The base type of the Iterator and Iterable.
| */
| public class IteratorToIterable<T> implements Iterable<T> {
| private Iterator<T> base;
| /**
| * Create an Iterable whose iterator method returns base.
| * @param base
| */
| public IteratorToIterable(Iterator<T> base){
| this.base = base;
| }
| /**
| * Get the Iterator passed to the constructor. The Iterator
| * should be used only once.
| */
| public Iterator<T> iterator() {
| return base;
| }
| }
|
| The intended use of this class is:
|
| public static void main(String[] args) {
| Iterator<Integer> it = getIterator();
| for(Integer i: new IteratorToIterable<Integer>(it) ){
| System.out.println(i);
| }
| }
I had some classes (Combinators, see
http://mindprod.com/jgloss/combination.html) which were iterators and
wanted to use them like this as well. I ended up having them implement
both Iterator<T> and Iterable<T>, with the iterator() function just
{return this;}. Not very elegant, but works as expected. I do remember
somebody had some valid remarks against that practice though,
particularly multiple iterations are a problem.
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org
iD8DBQFIDG4me+7xMGD3itQRArFnAJ0WM6Uwa84QrOE5l8nJdY/AWHg2sQCeO27g
/eHR6veCu8CBwndouc6xUww=
=1I0b
-----END PGP SIGNATURE-----