Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #34745

Two surprises in for (:)

From Mike Amling <mamling@chaff.us>
Newsgroups comp.lang.java.programmer
Subject Two surprises in for (:)
Date 2016-07-01 12:55 -0500
Organization A noiseless patient Spider
Message-ID <nl6apt$gg5$1@dont-email.me> (permalink)

Show all headers | View raw


I was surprised that the javac compiler accepted the following:

String[] foo={"a", "b"};
for (final String who : foo) {
}

because it seems strange to have a for loop's variable work when final. 
After all,

for (final int i=0; i<7; ++i) {
}

gets an error.

But for (final String who : foo) is more like an abbreviation of

for (final Iterator<String> iter=foo.iterator(); iter.hasNext(); ) {
   final String who=iter.next();
}

wherein it's not strange that who can be final.

My second surprise was that the compiler rejects

String[] foo={"a", "b"};
for (final Iterator<String> iter=foo.iterator(); iter.hasNext(); ) {
   final String who=iter.next();
}

apparently because arrays, unlike everything else accepted after the : 
in a for(:), do not actually implement the Iterable interface.

--Mike Amling
SSBzdXBwb3NlIGEgbG90IG9mIHlvdSBhcmUgbm90IHN1cnBpc2VkLg==

Back to comp.lang.java.programmer | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Two surprises in for (:) Mike Amling <mamling@chaff.us> - 2016-07-01 12:55 -0500
  Re: Two surprises in for (:) Eric Sosman <esosman@comcast-dot-net.invalid> - 2016-07-01 15:07 -0400
    Re: Two surprises in for (:) Daniel Pitts <usenet@coloraura.com> - 2016-07-01 15:08 -0700

csiph-web