不明显的数组索引
最近我在一个项目中看到很多类似的代码块,它们的编写方式如下:
String usedAlphabet = "x3w4tnu34urgbgierg";
byte c = // (something initialized earlier)
return usedAlphabet[(int)(c / 16)];
现在,在访问相应数组时使用 (int)
转换的原因可能是什么?
对我来说,这似乎是多余的,但我可能是错的,或者我可能缺乏关于类型转换机制的知识。
Recently I saw a lot of similiar code chunks in one project, which were written the following way:
String usedAlphabet = "x3w4tnu34urgbgierg";
byte c = // (something initialized earlier)
return usedAlphabet[(int)(c / 16)];
Now, what might be the reason to use the (int)
cast while accessing the corresponding array?
To me, it seems redundant, but I might be wrong or I may lack knowledge about the type casting mechanics.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你是对的;这里是多余的。有时,冗余转换可以使用法对读者来说更加明显,但这取决于上下文。
You are right; it is redundant here. Sometimes a redundant cast can make the usage more obvious to the reader, but that would depend on the context.
你是对的 - 除法是整数除法,它总是会产生一个整数,所以不需要强制转换。
然而,
c
本身缺乏上下文(特别是如果它没有被定义为接近此用法),因为它可能不明显这是一个byte / int
。添加演员表可能是为了提高可读性。You are right - the division is integer division which will always result in an integer, so the cast is not needed.
However,
c
by itself lacks context (especially if it was not defined close to this usage), as it may no be obvious that this is abyte / int
. It is possible that the cast was added as a readability aid.由于
c
是byte
且16
是int
,因此除法的结果是int
,使强制转换变得多余。然而,在某一时刻,c
的声明可能类似于long
或double
,并且需要进行强制转换。当声明改变时,演员阵容从未被删除。Since
c
is abyte
and16
is anint
, the result of the division is anint
, making the cast redundant. However it's possible that at one point the declaration ofc
was something likelong
ordouble
and the cast was needed. When the declaration was changed the cast was never removed.正如您已经发现的,演员阵容是多余的。它有助于提高可读性吗?也许吧,取决于上下文。可以做些什么来真正提高这种“不明显的数组索引”的可读性?我告诉你一些好名字(当然,作者应该找到能够传达他的意图的正确名称,我只是在这里编造的):
As you already found out, the cast is redundant. Does it aid in readability? Maybe, depending on the context. What could be done to really aid the readability of this "unobvious array indexing"? Good names I tell you (of course, the author should find the right names that communicate his intent, I've just made them up here):
我猜想,这个演员阵容来自于一个不清楚该语言的打字规则的开发人员,因此采用了“安全总比抱歉好”的方法。我怀疑我们大多数人都曾在某个时候这样做过。话虽如此,演员阵容是不需要的,甚至没有澄清。
I would guess that the cast from from a developer who is unclear on the rules of typing for the language, and so adopted a "better-safe-than-sorry" approach. I suspect most of us have done that at some point. That being said - the cast is unneeded and not even clarifying.