Avoid throwing java.lang.IndexOutOfBoundsException
Refactored and added tests