5 ms·
am I the only one that when looking at the implementation sees that there is a major flaw in the code? if(toIndex > arrayLen) does not handle the case in which
by holtalanm 10y ago
am I the only one that when looking at the implementation sees that there is a major flaw in the code?
if(toIndex > arrayLen) does not handle the case in which toIndex == arrayLen, which should still throw an ArrayIndexOutOfBoundsException if we are dealing with 0-based indexes.
Please correct me if I am wrong.
- worldsayshi 10y agoAlso the code isn't syntactically correct: (int arrayLen, int fromIndex, int toIndex { Missing parenthesis after toIndex. Something is fishy here.
- moron4hire 10y agoMaybe it's transcription error. Probably a paralegal somewhere copied it from the original source to a different document and doesn't have the programmer's eye for noticing minor differences in what would basically be line-noise to them.
- BurningFrog 10y agoSomeone copied it by hand, most likely.
- ddlatham 10y agoRanges are usually specified with the lower bound being inclusive and the upper bound exclusive. In this case [fromIndex, toIndex) So if the range goes to the end of the arrary, then you would expect toIndex == arrayLen and the check is correct.
- mannykannot 10y agoIs that consistent with the first condition in the function? This function accepts fromIndex == arrayLen if toIndex == arrayLen. Of course, there may be a precondition that rules it out, or it might be an acceptable postcondition.
- thaumasiotes 10y agoUnder the scheme described, fromIndex == toIndex would be a stretch of 0 array elements, so it wouldn't really matter whether fromIndex and toIndex pointed into the array at all.
- mannykannot 10y agoDoh! - thanks.
- hathym 10y agoagree, should be if (toIndex >= arrayLen)
- ArkyBeagle 10y agoIf an index of of the closed interval 0...arrayLen-1, then no. If the array index is of the closed interval 1 ... arrayLen, then yes. Shame on the second case; that war was fought decades ago and it lost. FORTRAN indexing is Bad.
- GeneralMayhem 10y agoAre upper bounds not generally exclusive in Java? I've been writing almost exclusively C++ for the past few years so I can't remember, but in C++ APIs are almost always set up so that you can pass the length of the container (or, equivalently but much more commonly, the end() iterator, which points just past the last element) as the upper bound of a range.
- gefh 10y agoWithout looking back at the article, I am willing to bet that Josh Bloch did not make that mistake.