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;
| }
| }
I would add
public static <T> Iterable<T> toIterable(Iterator<T> base) {
~ return new IteratorToIterable<T>(base);
}
(this is a pattern much seen in Jakarta Commons)
and then
| public static void main(String[] args) {
| Iterator<Integer> it = getIterator();
| for(Integer i: toIterable(it) ){
| System.out.println(i);
| }
| }
with a proper static import.
One could even just put that method somewhere in the class where one
wants to use it.
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
iD4DBQFIDGwEe+7xMGD3itQRAkgEAJ9httlWOlSauKtrNvoXi5edXjtB8ACXUNF5
GnELu8MWNBn1IYW71SD7hg==
=jpMA
-----END PGP SIGNATURE-----