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


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

Two surprises in for (:)

Path csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail
From Mike Amling <mamling@chaff.us>
Newsgroups comp.lang.java.programmer
Subject Two surprises in for (:)
Date Fri, 1 Jul 2016 12:55:20 -0500
Organization A noiseless patient Spider
Lines 34
Message-ID <nl6apt$gg5$1@dont-email.me> (permalink)
Mime-Version 1.0
Content-Type text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding 7bit
Injection-Date Fri, 1 Jul 2016 17:55:09 -0000 (UTC)
Injection-Info mx02.eternal-september.org; posting-host="cfefecc818af8c8edb17bddf4243dac6"; logging-data="16901"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/9vKGKvR4zoWdFAkS+vYd2"
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Thunderbird/45.1.1
X-Mozilla-News-Host news://news.eternal-september.org:119
Cancel-Lock sha1:ZIZl616zojPt6cbAVmQ6+Se1G3w=
Xref csiph.com comp.lang.java.programmer:34745

Show key headers only | 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