Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: Using Enumerated Types as Array Indexes Date: Sat, 20 Aug 2011 00:26:04 +0200 Lines: 62 Message-ID: <9b8687Fa7tU1@mid.individual.net> References: <4e4b0d81$0$314$14726298@news.sunsite.dk> <4e4b1fe4$0$314$14726298@news.sunsite.dk> <6d418cda-dab3-43df-a9ec-293b43f2bbd8@glegroupsg2000goo.googlegroups.com> <4e4cdfab$0$2524$da0feed9@news.zen.co.uk> <9b74tiFf06U1@mid.individual.net> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net yHD1NqJj+uEoPddhbu/q+wKzLt2OKj32MRxnn7x9isQhZd2as= Cancel-Lock: sha1:NoeJT6+m1HqgXEEJ64l+fZfwdnY= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:6.0) Gecko/20110812 Thunderbird/6.0 In-Reply-To: Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7257 On 20.08.2011 00:12, Arved Sandstrom wrote: > On 11-08-19 05:10 PM, Andreas Leitgeb wrote: >> Robert Klemme wrote: >>> byte b = 0xA0; // won't compile >> >> Actually, it *does* compile due to some special rule in >> the JLS w.r.t initializers. Andreas, which rule and which compiler? >> That, however doesn't impact the the point you made. >> Had you just written it thusly: >> byte b; b = 0xA0; // won't compile >> it would have been correct altogether. :-) >> > Not with JDK 1.6 it doesn't compile. I usually test these things if I'm > talking about them, mainly to avoid looking like a complete dilettante > in the case that I am overlooking something basic. This scenario, and > many permutations, I tried. Same here: Eclipse's compiler refuses both with "Type mismatch: cannot convert from int to byte". > "possible loss of precision" errors are reported if you try to compile > with outside range integer literals assigned to byte, short or char > variables, without casts. It doesn't matter if you try > > byte b = 128; > > or > > byte b; b = 0x80; > > either will error with a "possible loss of precision" message. Also, I cannot see any reason why these two situations should be treated differently: the loss of precision is there regardless. > Since it's routine and OK to create values of type byte, short, int and > long from int literals (and longs from long literals also), and a cast > is redundant for such an integer literal assignment, _and_ because a > cast masks the error, I would suggest that assignments with casts such as > > byte b = (byte)0xA0; > > or > > byte b = (byte)intVariable; > > be strenuously avoided. That's certainly a good rule of thumb which helps keeping one out of trouble. Although it sometimes seems reasonable to use values in the range [0x80, 0xFF] e.g. when defining bit masks. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/