Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Mike Amling 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: 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 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 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 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==