Apparently I've been living under a rock because I never seen
a negative array index before. Apparently python supports this,
but I've never found python interesting enough to bother with. Tcl
had the "end" keyword for list access, but you couldn't do anything more
(like end-1). Ruby has it, and as I use it more and more in Ruby
I really have started to like it.
The idea is simple. A negative array index is computed from the end
of the array:
String[] words = {"this", "is", "a", "test"};
System.out.println("The last word is " + words[-1]);
Is words[-1] really that much better than words[words.length-1]?
I think so. I tend to make a lot of dumb array/collection mistakes,
so it's definitely good on that point. I think -1 captures the idea
that I want the last item much better than words.length-1. This is
even more true for other values. Which says "second to last element"
better: -2 or words.length-2?
Having this available in strings and collections would be nice
too, but there is a little bit of a mismatch since substrings in java
are not inclusive of the rightmost index. word.substring(0,2) is two
characters in Java, but word[0..2] in ruby is three characters. Thus,
for consistency, word.substring(0,-1) in Java would have to imply all
the characters up to, but not including the last one. (word[0..-1] in
ruby would return the entire string) To be fair to Java, the Java
notation does let you express zero length substrings/subsets:
word.substring(0,0). So, you lose some expressiveness either way.
Regardless, I have found negative array bounds to be quite intuitive
and I miss not being able to use them in Java.