Hacker News new | past | comments | ask | show | jobs | submit login

the irony is that there is a bounds check already within the str.charAt() method...



That throws an exception though, while this code is trying to return 0. The java "fix" would be to add a charAtOrDefault(), but that doesn't seem to exist.

The source of charAt is also interesting because it manually bounds checks while the array access into the underlying char[] has its own bounds check. I'm not sure why having the separate exception is better than letting the array access throw directly?

https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/19fb8f93c...


Agreed. Though catching and handling that exception maybe more performant if majority of those indexes are within the bounds of the array.

>> I'm not sure why having the separate exception is better than letting the array access throw directly?

(1) The original String charAt method (Sun/Oracle) had to account for an offset and an index. The exception from the bounds check on the underlying char[] would be misleading/confusing... and therefore the birth of the seperate StringIndexOutOfBoundsException

Source: http://www.docjar.com/html/api/java/lang/String.java.html

(2) Because of the above and for backward compatibility, the OpenJDK is doing the same exception handling... sometimes it pays to review the original source code to get some context and rationale to the OpenJDK version.


Oh that makes sense, I had forgotten about the old substring sharing optimization.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: