40

Everywhere else in Java, anything with an index starts at 0. Is there a reason for the change here or is this just bad design?

TheTXI
  • 37,429
  • 10
  • 86
  • 110
Paul Wicks
  • 62,960
  • 55
  • 119
  • 146
  • 4
    I was wondering the same thing, especially since ResultSets are also 1-indexed. – Uri Apr 03 '10 at 20:24

6 Answers6

43

Historically, databases have used 1-based indexing for bound parameters. This probably reflects the origins of relational databases in set theory and mathematics, which index elements starting with one, and use zero to represent a null or empty set.

In shell scripts and regular expressions, the zero index usually means something "special". For example, in the case of shell scripts, the zeroth "argument" is actually the command that was invoked.

The choice for JDBC was deliberate but, ultimately, probably causes more confusion and difficulty than it solves.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • 1
    In mathematics it's usually easier to go with zero-indexing (in my experience (third class BSc)). – Tom Hawtin - tackline Mar 05 '09 at 19:18
  • 4
    I don't think zero-based indexing is a mathematical artifact. Every linear algebra book I have starts numbering rows/columns with 1. FORTRAN defaults from 1, if I recall correctly. I think zero-based indexing is a legacy from C and pointer arithmetic. – duffymo Mar 05 '09 at 20:24
  • 2
    Personally, I think 0-based indexing is a throwback from C pointer arithmetic which seems to have stuck... to the misfortune of us all. – Lawrence Dol Mar 06 '09 at 06:32
  • 4
    The beauty of using 0-based indexing is: You can use the interval containing consecutive `N` elements as `[0, N)` and `[N, 2N)`, `[2N, 3N)` and so on so forth. So all mainstream languages like C, C++, Java, JavaScript, Python use the 0-based index convention originally used in C programming language. This principle also applies to generic index like `[a, b)` where `a` is inclusive and `b` is exclusive. – tonga Dec 06 '13 at 02:47
21

This was part of a plot by the original language designers to weed out the weak. In the original spec, arrays were numbered from -1, and lists with 1 element returned length =0.

Today, only the java Calendar API remains from this diabolical plot.

Steve B.
  • 55,454
  • 12
  • 93
  • 132
2

Personally I would chalk this up to bad design.

matt b
  • 138,234
  • 66
  • 282
  • 345
2

I understand both JDBC and ODBC are based upon the X/Open Call Level Interface. So, it's pre-Java history, like 0-based month numbers.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
0

Likely it's that JDBC was modeled on ODBC.

Dave Costa
  • 47,262
  • 8
  • 56
  • 72
0

More human friendly maybe? Also, Java's regular expression Matcher's group starts with 1 as the first matched group.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257