Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Generics and for each

Reply
Thread Tools

Generics and for each

 
 
Tom McGlynn
Guest
Posts: n/a
 
      11-07-2008
Recently I've been trying to implement Iterable in some of my classes
to take advantage of the for-each syntax, e.g., to loop over the
results in a query. It doesn't work quite as nicely as I would like
due -- I think -- to non-reifiability of generics. Here's an example
that illustrates
the problem.

import java.util.ArrayList;
import java.util.Iterator;

public class Zz implements Iterable {

ArrayList<String> arr = new ArrayList<String>();
Zz() {
arr.add("a");
arr.add("b");
arr.add("c");
}

public Iterator<String> iterator() {
return arr.iterator();
}
public static void main(String[] args) {

Zz z = new Zz();

for (String x: z) {
System.out.println(x);
}
}
}

This fails with an incompatible types message when compiling the for
loop.

If I replace 'String x' with 'Object x' all is copacetic, but as it
stands it fails because it doesn't know that the Iterator is a
<String> iterator. I gather that's information lost due to type
erasure.

Am I misunderstanding the idiom I need to do this, or do I still need
to do the kinds of casts
that generics were supposed to help me get rid of. I.e., is there any
operational advantage of specifying
public Iterator<X> iterator()
versus
public Iterator iterator()
when X is a real class not a generic type. [Presumably it's still a
good thing to do for documentation.]

I've no doubt this has come up before -- if you can point to some
earlier discussion or documentation I'd appreciate it.

Regards,
Tom McGlynn
 
Reply With Quote
 
 
 
 
Joshua Cranmer
Guest
Posts: n/a
 
      11-07-2008
Tom McGlynn wrote:
> Recently I've been trying to implement Iterable in some of my classes
> to take advantage of the for-each syntax, e.g., to loop over the
> results in a query. It doesn't work quite as nicely as I would like
> due -- I think -- to non-reifiability of generics. Here's an example
> that illustrates
> the problem.
>
> public class Zz implements Iterable {


Here's your problem. Iterable is a generic class: you want Iterable<String>.

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
 
Reply With Quote
 
 
 
 
Tom McGlynn
Guest
Posts: n/a
 
      11-07-2008
On Nov 7, 1:18 pm, Joshua Cranmer <Pidgeo...@verizon.invalid> wrote:
> Tom McGlynn wrote:
> > Recently I've been trying to implement Iterable in some of my classes
> > to take advantage of the for-each syntax, e.g., to loop over the
> > results in a query. It doesn't work quite as nicely as I would like
> > due -- I think -- to non-reifiability of generics. Here's an example
> > that illustrates
> > the problem.

>
> > public class Zz implements Iterable {

>
> Here's your problem. Iterable is a generic class: you want Iterable<String>.
>
> --
> Beware of bugs in the above code; I have only proved it correct, not
> tried it. -- Donald E. Knuth



Thanks...
I should have realized that such a simple case had to work,
Regards,
 
Reply With Quote
 
Tom McGlynn
Guest
Posts: n/a
 
      11-07-2008
On Nov 7, 1:18 pm, Joshua Cranmer <Pidgeo...@verizon.invalid> wrote:
> Tom McGlynn wrote:
> > Recently I've been trying to implement Iterable in some of my classes
> > to take advantage of the for-each syntax, e.g., to loop over the
> > results in a query. It doesn't work quite as nicely as I would like
> > due -- I think -- to non-reifiability of generics. Here's an example
> > that illustrates
> > the problem.

>
> > public class Zz implements Iterable {

>
> Here's your problem. Iterable is a generic class: you want Iterable<String>.
>
> --
> Beware of bugs in the above code; I have only proved it correct, not
> tried it. -- Donald E. Knuth


Thanks... I should have realized that such a simple case had to work
and I'd made an error somewhere.
Tom
 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      11-07-2008
Tom McGlynn wrote:
> Recently I've been trying to implement Iterable in some of my classes
> to take advantage of the for-each syntax, e.g., to loop over the
> results in a query. *It doesn't work quite as nicely as I would like
> due -- I think -- to non-reifiability of generics. *



That's not the reason. The issue occurs at compile time, therefore it
cannot be related to reifiability, which is a run-time issue.

You left out the type parameter on the 'implements Iterable' clause,
so the compiler has no way of matching the 'String' type of the loop
variable to the underlying type of the 'Iterable'.

Add a generic type parameter as indicated below. I used 'String' to
match your example, but it'd be better as '<T>'.

> import java.util.ArrayList;
> import java.util.Iterator;
>
> public class Zz implements Iterable


<String> // got to nail down what *type* of Iterable it is

> {
> * * ArrayList<String> arr = new ArrayList<String>();


// consider using: List <String> arr = new ArrayList <String> ();

> * * Zz() {
> * * * * arr.add("a");
> * * * * arr.add("b");
> * * * * arr.add("c");
> * * }
>
> * * public Iterator <String> iterator() {


// Because you didn't implement 'Iterator <String>'
// the compiler cannot resolve your type in the 'main()' for-each
loop.

> * * * * return arr.iterator();
> * * }
> * * public static void main(String[] args) {
>
> * * * * Zz z = new Zz();
>
> * * * * for (String x : z) {
> * * * * * * System.out.println(x);
> * * * * }
> * * }
>
> }
>
> This fails with an incompatible types message when compiling the for
> loop.


Always but always cite the actual error message, character for
character, preferably by copy-and-paste, rather than paraphrasing.

> If I replace 'String x' with 'Object x' all is copacetic, but as it
> stands it fails because it doesn't know that the Iterator is a
> <String> iterator. *I gather that's information lost due to type
> erasure.


Nope. It's a compile-time issue, as you stated. Type erasure is a
run-time phenomenon, and you would not have discovered it via a
compile-time message.

> Am I misunderstanding the idiom I need to do this,


Yes.

> or do I still need to do the kinds of casts


Nope.

> that generics were supposed to help me get rid of. *I.e., is there any
> operational advantage of specifying
> * * public Iterator<X> iterator()
> versus
> * * public Iterator iterator()
> when X is a real class not a generic type.


Not if you neglect the type parameter in the 'implements' clause,
there isn't.

Even better than '<String>':

<sscce>
package eegee;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/** Zz illustrates how to implement <code>Iterable</code>.
* @param <T> generic type of iterator.
*/
public class Zz <T> implements Iterable <T>
{
List <T> arr = new ArrayList <T> ();

@Override
public Iterator <T> iterator()
{
return arr.iterator();
}

/** Add an element.
* @param val <code>T</code> element to add.
* @return boolean <code>true</code> iff the add succeeds.
*/
public boolean add( T val )
{
return arr.add( val );
}

/** Main method.
* @param args <code>String []</code> arguments.
*/
public static void main( String [] args )
{
Zz <String> z = new Zz <String> ();

z.add( "a" );
z.add( "b" );
z.add( "c" );

for ( String x : z )
{
System.out.println(x);
}
}
}
</sscce>

run:
a
b
c
BUILD SUCCESSFUL (total time: 1 second)

--
Lew
 
Reply With Quote
 
Tom McGlynn
Guest
Posts: n/a
 
      11-07-2008
Thanks again to you and Joshua. Should know better than to post after
only a couple of hours sleep!

I suspect I would have looked at it for a long long time without
realizing what I was doing wrong.
Regards,
Tom McGlynn
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      11-08-2008
On Fri, 7 Nov 2008 09:42:59 -0800 (PST), Tom McGlynn
<> wrote, quoted or indirectly quoted
someone who said :

>public class Zz implements Iterable {


You meant:

public class Zz implements Iterable<String> {

Lots of redundancy required with generics.
--
Roedy Green Canadian Mind Products
http://mindprod.com
Your old road is
Rapidly agin'.
Please get out of the new one
If you can't lend your hand
For the times they are a-changin'.
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      11-08-2008
On Fri, 7 Nov 2008 09:42:59 -0800 (PST), Tom McGlynn
<> wrote, quoted or indirectly quoted
someone who said :

>
>public class Zz implements Iterable {


see http://mindprod.com/jgloss/iterator.html#ITERABLE
for sample code.
--
Roedy Green Canadian Mind Products
http://mindprod.com
Your old road is
Rapidly agin'.
Please get out of the new one
If you can't lend your hand
For the times they are a-changin'.
 
Reply With Quote
 
Mike Schilling
Guest
Posts: n/a
 
      11-08-2008
Tom McGlynn wrote:
> Thanks again to you and Joshua. Should know better than to post
> after
> only a couple of hours sleep!
>
> I suspect I would have looked at it for a long long time without
> realizing what I was doing wrong.


Sometimes, especially when you know that the problem is something
simple but you can't find it, the key is to *stop* looking at it for a
while. Take a nap, go for a walk, read a book, or whatever you think
will clear your mind, and then come back and look at it with fresh
eyes. I couldn't begin to tell you how many times after I've spent
all day fighting with something I've figured it out on the drive home.


 
Reply With Quote
 
Joshua Cranmer
Guest
Posts: n/a
 
      11-08-2008
Mike Schilling wrote:
> Tom McGlynn wrote:
>> Thanks again to you and Joshua. Should know better than to post
>> after
>> only a couple of hours sleep!
>>
>> I suspect I would have looked at it for a long long time without
>> realizing what I was doing wrong.

>
> Sometimes, especially when you know that the problem is something
> simple but you can't find it, the key is to *stop* looking at it for a
> while. Take a nap, go for a walk, read a book, or whatever you think
> will clear your mind, and then come back and look at it with fresh
> eyes. I couldn't begin to tell you how many times after I've spent
> all day fighting with something I've figured it out on the drive home.


I have at least two separate instances where I've been stuck on a
problem and gave up. As I was thinking to myself later in the shower,
the answer revealed itself with a clear, perfect resolution. Makes me
feel like Archimedes.

Disclaimers: Both the problems were programming problems, not problems
of determining density. Also, I did not run through the house or city
naked. I had a bathrobe on.

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Transform a 2D color image into 2 images of (R1,G1,B) at each pixelof image 1 and (R2,G2,B) at each pixel of image2 for STEREO visualization 88888 Dihedral C++ 10 12-23-2011 02:28 PM
generics depending on generics Soul VHDL 0 02-02-2009 09:14 AM
multiD-vhdl: Multi Dimensional Arrays (allowing generics on each dimension) for VHDL (including ports) albert.neu@gmail.com VHDL 2 03-21-2006 04:05 PM
Array#each - getting each element and the index Pat Maddox Ruby 6 01-20-2006 04:04 PM
Can't convert a generics list of objects into a generics list ofinterfaces Juergen Berchtel Java 1 05-20-2005 02:07 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57